Greedy Algorithms

Lesson 18 of 20

Watch a meeting room fill by earliest finish, then count out 63 in coins — one irrevocable greedy choice at a time.

The big picture

The greedy contract

A greedy algorithm makes the best-looking choice right now, commits to it, and never looks back. When the rule is right, that single sweep beats any exhaustive search.

The contract

Take the locally best option, commit irrevocably, move on. No undo, no dp table — usually just a sort followed by one O(n) pass.

Earliest finish wins

Activity selection sorts meetings by end time and books every one that fits: A(1-3), C(4-7) and F(8-10) fill the room — 3 of the 6 requests.

Why it is safe

The meeting that ends earliest leaves the most room behind it. The exchange argument shows swapping it into any schedule never loses a meeting.

Coins, biggest first

Change 63 from {25, 10, 5, 1}: 25 + 25 + 10 + 1 + 1 + 1 — 6 coins. On this canonical set greedy is provably optimal.

When greedy fails

Coins {4, 3, 1}, amount 6: greedy pays 4 + 1 + 1 (3 coins) while 3 + 3 needs just 2. Non-canonical systems break the rule.