Greedy Algorithms

Lesson 18 of 20

Watch a cashier grab the biggest coin that fits and a scheduler pack the most activities — one choice at a time, never looking back.

The big picture

Why greedy works

A greedy algorithm takes the locally best choice at every step and never revisits it — blazing fast when that choice is provably safe.

The greedy choice

Grab whatever looks best right now — the biggest coin, the earliest-finishing task — and lock it in forever.

Coin change

63¢ from {25, 10, 5, 1} takes six coins: 25 + 25 + 10 + 1 + 1 + 1 — found by always taking the biggest that fits.

Activity selection

Sort by finish time, keep every activity with start ≥ lastEnd — three of these five activities survive.

Proof by exchange

Swap any optimal solution toward the greedy one, piece by piece — if the value never drops, greedy is optimal.

The trap

Coins {1, 3, 4} and amount 6: greedy pays 4+1+1 = 3 coins, but 3+3 = 2. Fast is not always right.