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: 2
💡 Note: From index 0 (value 4), we can jump to indices 1, 2, or 3. However, from index 2 we cannot reach index 3 since |1-5|=4 > target=3. The optimal path is 0→1→3, giving us 2 jumps maximum.
Example 2 — Limited Jumps
$ Input: nums = [3,5,7], target = 1
Output: -1
💡 Note: From index 0 (value 3), we cannot jump to index 1 since |5-3|=2 > target=1, and we cannot jump to index 2 since |7-3|=4 > target=1. Therefore, it's impossible to reach the end.
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 to Reach Last Index INPUT nums array: 4 i=0 2 i=1 5 i=2 1 i=3 target = 3 Jump condition: -3 <= nums[j]-nums[i] <= 3 Possible jumps from i=0: 0-->1: |2-4|=2 OK 0-->2: |5-4|=1 OK 0-->3: |1-4|=3 OK ALGORITHM STEPS 1 Initialize DP dp[0]=0, others=-1 2 For each index j Check all valid i < j 3 Update dp[j] dp[j] = max(dp[j], dp[i]+1) 4 Return dp[n-1] Max jumps to last index DP Table Evolution: Init: [0, -1, -1, -1] j=1: [0, 1, -1, -1] j=2: [0, 1, 2, -1] j=3: [0, 1, 2, 3] FINAL RESULT Optimal Jump Path: i=0 4 i=1 2 i=2 5 i=3 1 Jump sequence: 0 --> 1 --> 2 --> 3 Jump 1: |2-4|=2 <= 3 OK Jump 2: |5-2|=3 <= 3 OK Jump 3: |1-5|=4 <= 3 OK Output: 3 Key Insight: Dynamic Programming finds the MAXIMUM jumps by exploring all valid paths. For each index j, we check all previous indices i where the jump is valid (difference <= target). The recurrence dp[j] = max(dp[i] + 1) ensures we count the maximum possible jumps to reach each position. Time: O(n^2), Space: O(n). TutorialsPoint - Maximum Number of Jumps to Reach the Last Index | DP Approach
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