Greedy Algorithms

Lesson 18 of 20

Sort meetings by finish time and book them greedily — then watch coins {4, 3, 1} trip the strategy that 25/10/5/1 never trips.

The big picture

Why greedy works

One pass, one sort, zero regret: greedy bets that the locally best choice never needs undoing — and usually the bet pays.

The greedy deal

Take the locally best move now and never reconsider. One pass, tiny state, instant answers — no table, no recursion.

The sort is the strategy

Activity selection sorts by finish time: the earliest finisher leaves the most room behind it — 6 bookings, one comparison each.

One variable of state

The whole scan needs last_end — start ≥ last_end means compatible, and back-to-back (4 ≥ 3) counts as a fit.

Greedy works… usually

Canonical coins like {25, 10, 5, 1} split any amount optimally biggest-first: 87 needs exactly 25+25+25+10+1+1.

…and how it fails

Coins {4, 3, 1}, amount 6: greedy takes 4+1+1 (3 coins); optimal is 3+3 (2). No sort key can save it.

The proof move

Exchange argument: swap any optimal pick for the greedy one — the solution stays valid, so greedy was safe all along.