Maximum Number of Jumps to Reach the Last Index - Problem
Imagine you're on a magical stepping stone path across a river! ๐ You start at the first stone (index 0) and need to reach the last stone (index n-1) to complete your journey.
Here's the twist: each stone has a magical number on it, and you can only jump from stone i to stone j if:
- You're jumping forward:
i < j - The magical numbers are similar enough:
|nums[j] - nums[i]| <= target
Your goal is to find the maximum number of jumps you can make to reach the final stone. If it's impossible to reach the end, return -1.
Example: With stones [1, 3, 6, 4, 1, 2] and target = 2, you could jump: 0โ1โ3โ5 (3 jumps) or 0โ2โ4โ5 (3 jumps).
Input & Output
example_1.py โ Basic Path Finding
$
Input:
nums = [1, 3, 6, 4, 1, 2], target = 2
โบ
Output:
3
๐ก Note:
One optimal path is 0โ1โ3โ5: jump from index 0 to 1 (|3-1|=2โค2), then 1 to 3 (|4-3|=1โค2), then 3 to 5 (|2-4|=2โค2). This gives us 3 jumps total.
example_2.py โ No Valid Path
$
Input:
nums = [1, 0, 2], target = 0
โบ
Output:
-1
๐ก Note:
From index 0 (value=1), we cannot jump to index 1 (value=0) because |0-1|=1 > 0. We also cannot jump to index 2 (value=2) because |2-1|=1 > 0. No path exists.
example_3.py โ Single Jump
$
Input:
nums = [1, 3], target = 5
โบ
Output:
1
๐ก Note:
We can jump directly from index 0 to index 1 because |3-1|=2โค5. This requires exactly 1 jump, which is optimal since we need to reach the last index.
Constraints
- 1 โค nums.length โค 1000
- 0 โค nums[i] โค 105
- 0 โค target โค 2 ร 105
- Must jump forward only: i < j for valid jumps
- Jump constraint: |nums[j] - nums[i]| โค target
Visualization
Tap to expand
Understanding the Visualization
1
Start at first stone
Begin your journey at stone 0 with nums[0] = 1
2
Find valid jumps
Look for stones you can jump to: |destination_value - current_value| โค target
3
Choose optimal path
Instead of the shortest path, choose the path with maximum jumps
4
Reach the end
Successfully arrive at the final stone with maximum scenic stops
Key Takeaway
๐ฏ Key Insight: This problem asks for the *maximum* number of jumps (longest path), not the minimum. We use DP to track the maximum jumps to reach each position, building up the solution iteratively.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code