Ctrl K

As Many Hops as Possible

Medium
Stones lie in a row across a river, and heights[i] is the height of stone i. A frog sits on stone 0 and wants to reach the last stone. Each hop goes forward only, from stone i to any stone j > i, and the two heights may differ by at most step: |heights[j] - heights[i]| ≤ step. The frog loves hopping, so it wants to reach the last stone using as **many** hops as possible. Return that number, or -1 if the last stone cannot be reached at all.
Example 1
heights=[0, 5, 2, 3, 9, 1], step=2 → 3

The best route is 0 → 2 → 3 → 1 (indices 0, 2, 3, 5), three hops. The stones at heights 5 and 9 are too far from the others.

Example 2
heights=[4, 10, 20], step=5 → -1

No stone is close enough in height to the last one (20), so the answer is −1.

Example 3
heights=[7, 7, 7, 7], step=0 → 3
Constraints
  • 2 ≤ len(heights) ≤ 1000
  • -10⁹ ≤ heights[i] ≤ 10⁹
  • 0 ≤ step ≤ 2·10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
heights=[0, 5, 2, 3, 9, 1], step=2
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 144 tests on the server, hidden ones included.