synopsis · Paradigms · chapter 32
Greedy Algorithms
8 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Greedy = take the best-looking choice now and never undo it. Fast (one sort + one pass), but only right with a proof.
- use it when
One choice is always safe: furthest reach, restart after a failure, smallest card first. Can't say why in one line? Suspect DP.
- template
Sort by the key that makes the choice obvious → one loop → a few variables of state (
reach,tank,lo/hi). - cost
Usually O(n) for the pass, O(n log n) with a sort. DP for the same problem is often O(n²); brute force is 2ⁿ.
- trap
Coins {1, 3, 4}, amount 6: biggest-first pays 4+1+1 (3 coins), but 3+3 is 2. Test 2–3 tiny inputs before trusting greedy.
- trap
Gas Station: the restart finds a candidate, but only
total >= 0says a start exists. Skip it and you return a wrong index. - pro tip
Prove it out loud: exchange (swap any best answer's choice for mine, no worse) or stays ahead (my
reachis never behind). - pro tip
Unknown choices? Track a range. LC 678 keeps
lo/hiopen counts instead of trying all 3ᵏ meanings of the stars.
Shaky on a card? Open the chapter or flip its recall cards.