Show problems as
Classic problem #2770MediumArrayDynamic Programming

Maximum Number of Jumps to Reach the Last Index

Real-world version: Most Stones on the Way Across
Tracked in this browser only
Read Maximum Number of Jumps to Reach the Last Index on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Stepping stones sit in a line with heights nums. From the stone at position i you may step forward to any stone at a later position j whose height differs from nums[i] by at most target, in either direction.

You start on the first stone. Return the largest number of steps a crossing can take to reach the last stone, or -1 when the last stone cannot be reached at all.

Examples

Example 1

Input
nums = [4, 11, 6, 13, 9, 16], target = 5
Output
-1

Stepping 4 to 6 to 9 to 13 to 16 keeps every height change inside five and uses four steps, and no crossing manages more.

Example 2

Input
nums = [7, 7, 7, 7, 7], target = 0
Output
4

Every stone is the same height, so every step is allowed and the crossing can take them one at a time.

Example 3

Input
nums = [1, 3, 6, 4, 1, 2], target = 0
Output
-1

With no allowance a step needs two stones of equal height, and no such step reaches the last stone.

Constraints

  • 2 <= nums.length <= 1000
  • -10^9 <= nums[i] <= 10^9
  • 0 <= target <= 2 * 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def maximum_jumps(nums: list[int], target: int) -> int:
Java
public int maximumJumps(int[] nums, int target)