Greedy algorithms
The conceptWhy a cashier reaches for the biggest coin first
A greedy algorithm builds an answer step by step, always taking the choice that looks best right now and never undoing it. A cashier making 87 cents takes the biggest coin that fits, then the biggest that fits the rest.
It is fast but not always right. With coins of 1, 3 and 4, greedy pays 6 as 4 + 1 + 1, which is three coins, though 3 + 3 needs only two. Dynamic programming would compare both options. Greedy commits and never looks back.
What it’s forMakes change by always taking the largest coin that still fits.
c = largest coin ≤ r; r ← r − c (repeat until r = 0)
- r
- the amount still left to pay, in cents
- c
- the coin picked at this step
- ←
- update r to its new value
What it givesA list of coins that adds up to the amount, chosen without ever reconsidering a pick.
- Euro coins, 87¢: 50, 20, 10, 5, 2 → 5 coins, the fewest possible
- Coins {1, 3, 4}, 6¢: 4, then 1, 1 → 3 coins
- But 3 + 3 also makes 6, with only 2 coins: greedy missed it