Algorithm Day80 - Jump Game II
🧩 Problem Description
You are given a 0-indexed array of integers nums of length n. You are initially positioned at the first index.
Each element nums[i] represents the maximum length of a forward jump from index i.
Return the minimum number of jumps to reach the last index. The test cases are generated such that you can always reach the last index.
💬 Examples
Example 1
1 | Input: nums = [2,3,1,1,4] |
Example 2
1 | Input: nums = [2,3,0,1,4] |
💡 Intuition
This problem can be solved using a greedy approach.
- We want to minimize the number of jumps.
- Track two variables while scanning:
currentEnd: the farthest point reachable with the current number of jumps.farthest: the farthest point reachable by the next jump.
- Each time we reach
currentEnd, we must make another jump, and updatecurrentEnd = farthest.
This guarantees minimum jumps since we always extend as far as possible at each step.
🔢 Java Code (Greedy)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(n) — linear scan.
- Space: O(1).
✍️ Summary
- Use a greedy strategy to expand the farthest reach at each step.
- Each time you exhaust the current range, increment jumps and move to the next range.
- Efficient O(n) solution.
Related problems
lc-55— Jump Gamelc-1306— Jump Game IIIlc-1345— Jump Game IV