What is Jump Game II
Each element nums[i] is the maximum forward jump from index i. Return the minimum number of jumps to reach the last index. The classic problem promises that the last index is reachable.
Example. nums = [2, 3, 1, 1, 4] returns 2. Jump from index 0 to index 1, then from index 1 to index 4.
Input: 2 3 1 1 4 Output: 2
A second route, 0 to 1 to 4 on [2, 3, 0, 1, 4], is also 2 jumps. Jumping 0 to 2 lands on a 0 and wastes a jump.
Constraints. 1 ≤ n ≤ 104. The picture keeps n at 12.
Approach
Interactive visualization
The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index updates farthest at most once. |
| Space | O(1) | The window end, farthest index, and jump count are enough. |
| Greedy choice | Extend the window | The farthest landing in this window is the best place for the next jump to end. |
Implementation