Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 10 minutesNeeds: arraysTime O(n)Space O(1)

2 · Watch

Greedy in 60 seconds

Five stones hold jumps of 2, 3, 1, 1 and 4. Can you reach the end? Trying every route means following the same jumps again and again.

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.
  1. Medium01

    Maximum Subarray

    LeetCode 53 · Blind 75 · NeetCode 150

    Extend the running sum or restart it, keeping the best seen.

  2. Medium02

    Jump Game

    LeetCode 55 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

UP NEXT · LESSON 18 OF 20IntervalsSort by start, then merge or split.