Mediumgreedy
Jump Game II
Problem (restated)
Minimum jumps to reach last index (guaranteed reachable).
Intuition
Level-by-level: within current jump range, track farthest next end; when i hits end, jump++.
Approaches
Range BFS greedy
UnverifiedTime O(n)Space O(1)
Idea. curEnd, far; when i==curEnd, jumps++, curEnd=far.
Walkthrough. [2,3,1,1,4] → 2 jumps.
Trade-offs. Greedy levels vs DP min jumps O(n²).
Solution
export function jump(nums: number[]): number {
let jumps = 0, curEnd = 0, far = 0;
for (let i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]!);
if (i === curEnd) {
jumps++;
curEnd = far;
}
}
return jumps;
}
export function jump(nums: number[]): number {
let jumps = 0, curEnd = 0, far = 0;
for (let i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]!);
if (i === curEnd) {
jumps++;
curEnd = far;
}
}
return jumps;
}
Template connection
Greedy jump with range expansion.
Reflection
- The farthest jump inside the current window is the next window. The number of windows is the number of jumps.
- Stop once the last index is already inside this window.
[0]answers 0. A jump of 1 at every index isn - 1. - The windows are BFS layers. The greedy choice is the max reach inside the window.