public int jump(int[] nums) { int res = 0; int l = 0, r = 0; // window: indices reachable in res jumps while (r < nums.length - 1) { int farthest = 0; for (int i = l; i <= r; i++) { farthest = Math.max(farthest, i + nums[i]); } l = r + 1; r = farthest; res++; } return res;}
- res
- 0
- [l, r]
- —
- i
- —
- i + nums[i]
- —
- farthest
- —
Why it works
- Brute force is a DP:
jumps[j] = 1 + min(jumps[i])over everyithat reachesj. That is O(n²), or a BFS over an explicit graph with O(n²) edges. - The BFS levels are contiguous windows. If index
jis reachable withinresjumps, so is every index before it. So levelresis a window[l, r], and the next level runs fromr + 1to the farthest jump out of the window. - Each index is scanned once, inside exactly one window: O(n) time, and only
l,r,farthestandres: O(1) space. - Pitfall: loop while
r < nums.length - 1. Jumping once more after the window already covers the last index overcounts, and[0]needs 0 jumps. - Related: Jump Game (55) only asks whether the end is reachable. If
farthestever fails to passr, the window is stuck and the end is unreachable.