oneby7

1-D Dynamic Programming Take it or skip it

521. Frog Jump with K Steps

Easy

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

301060106050

Input: heights = [30, 10, 60, 10, 60, 50], k = 2

Output: 40

Explanation: 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

7396

Input: heights = [7, 3, 9, 6], k = 5

Output: 1

Explanation: 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

010⁹010⁹

Input: heights = [0, 1000000000, 0, 1000000000], k = 1

Output: 3000000000

Explanation: 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.

heights = [15, 5, 35, 10, 25, 40], k = 3

Constraints

  • 1 ≤ heights.length ≤ 105
  • 0 ≤ heights[i] ≤ 109
  • 1 ≤ k ≤ 100

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.