Greedy
Cross a stream on stepping stones without ever planning the route. From each stone, only note the farthest stone you could land on. If the next stone sits past that mark, the crossing is impossible, and you knew without retracing a step.
2 · Watch
Greedy in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Jump Game
or try
1–10 jump lengths from 0 to 5, separated by spaces.You stand on stone 0. So far you can reach stone 0.Step 1 of 7. 5 stones, jumps 2, 3, 1, 1, 4. Standing on stone 0. Farthest reachable stone 0.
Step 1 of 7
solution.ts
function canJump(nums: number[]): boolean {
let reach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > reach) return false;
reach = Math.max(reach, i + nums[i]);
}
return true;
}
▶ marks the line running now
4 · Your turn
0 of 2 problems solved
Start from this
// One running value sums up every choice so far.
let state = start;
for (const x of items) {
// Check you can still go on before choosing.
if (isStuck(state, x)) return fail;
// Take the best move now and never look back.
state = bestChoice(state, x);
}
return state;Easy ways to go wrong
- Trusting a greedy idea without a reason it can’t be beaten.
- Skipping the sort that makes the local choice safe.
- Tracking the whole route when one running number would do.
- Medium01
Maximum Subarray
Extend the running sum or restart it, keeping the best seen.
If the running total goes negative, drop it and restart.
- Time
- O(n)
- Space
- O(1)
Also works with 1-D DP or Sliding Window.
- Medium02
Jump Game
The one you just watched. Write it from memory.
Only the farthest reachable spot matters.
- Time
- O(n)
- Space
- O(1)
Also works with 1-D DP.