Maximum Number of Jumps to Reach the Last Index - Problem

You are given a 0-indexed array nums of n integers and an integer target.

You are initially positioned at index 0. In one step, you can jump from index i to any index j such that:

  • 0 <= i < j < n
  • -target <= nums[j] - nums[i] <= target

Return the maximum number of jumps you can make to reach index n - 1.

If there is no way to reach index n - 1, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,5,1], target = 3
Output: 3
💡 Note: From index 0 (value 4), we can jump to indices 1, 2, or 3. Optimal path: 0→1→2→3 gives us 3 jumps maximum.
Example 2 — Limited Jumps
$ Input: nums = [3,5,7], target = 1
Output: 1
💡 Note: From index 0 (value 3), we can only jump to index 2 (value 7) since |7-3|=4 > target=1 is false, but we can jump to index 1 first. Path: 0→2 gives 1 jump, or 0→1→2 but |7-5|=2 > 1.
Example 3 — No Path
$ Input: nums = [1,10], target = 2
Output: -1
💡 Note: From index 0 (value 1), we cannot reach index 1 (value 10) because |10-1| = 9 > target = 2.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ target ≤ 109

Visualization

Tap to expand
Maximum Number of Jumps: Find Longest Path4251Starti=1i=2Goal|2-4|≤3 ✓|5-2|≤3 ✓|1-5|≤3 ✓Path: 0 → 1 → 2 → 3 (3 jumps)Maximum jumps: 3
Understanding the Visualization
1
Input
Array [4,2,5,1] with target=3
2
Valid Jumps
Check which positions we can jump to based on value difference
3
Output
Maximum jumps possible: 3
Key Takeaway
🎯 Key Insight: We want to maximize jumps, not minimize them, so we explore all valid paths using dynamic programming
Asked in
Meta 15 Google 12 Amazon 8
18.5K Views
Medium Frequency
~25 min Avg. Time
745 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen