1-D Dynamic Programming Take it or skip it
521. Frog Jump with K Steps
There are n stones in a row, numbered from 0 to n − 1, and heights[i] is the height of stone i. A frog
sits on stone 0 and wants to reach the last stone, stone n − 1.
From stone i the frog can jump forward to any of the next k stones: stone i + 1, i + 2, and so on up
to i + k, as long as that stone exists. A jump from stone i to stone j costs
|heights[i] − heights[j]|, the difference between their heights. The frog never jumps backwards.
Return the smallest total cost of the jumps that take the frog from stone 0 to stone n − 1. With only one stone the frog is already there, and the answer is 0.
Example 1
Input: heights = [30, 10, 60, 10, 60, 50], k = 2
40Explanation: The cheapest route is 0 → 2 → 4 → 5, which costs 30 + 0 + 10 = 40. Starting with the cheapest first jump, to stone 1, leads to 0 → 1 → 3 → 5 and costs 20 + 0 + 40 = 60.
Example 2
Input: heights = [7, 3, 9, 6], k = 5
1Explanation: k = 5 is more than the frog needs, since it cannot jump past the last stone. It jumps from stone 0
straight to stone 3 for |7 − 6| = 1.
Example 3
Input: heights = [0, 1000000000, 0, 1000000000], k = 1
3000000000Explanation: With k = 1 the frog lands on every stone, and each of the three jumps costs 109.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ heights.length ≤ 1050 ≤ heights[i] ≤ 1091 ≤ k ≤ 100
Clarifying questions
What you would ask an interviewer before writing any code.