All problems
0905MediumArrayDynamic Programming

Most Stones on the Way Across

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2770Maximum Number of Jumps to Reach the Last Index

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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