Data Structures & Algorithms / Module 5: Algorithm patterns
Topic 5.4
Greedy
Take the best now and never look back: when it is right, and when it is quietly wrong.
Watch: each step takes the biggest coin that still fits. For rupiah that gives the fewest coins; for coins 1, 3 and 4 it doesn't.
- moving now
- finished / the result
A cashier giving change
A cashier gives 1,800 rupiah in change. Without much thought they take 1,000, then 500, then 200, then 100. Four coins, and that really is the fewest. For rupiah denominations, "biggest first" is always right.
Now picture coins worth 1, 3 and 4, and change of 6. Greedy takes 4, then 1, then 1: three coins. But 3 + 3 is only two. Choose the second example in the figure. Taking 4 looks best at the start, but it shuts the door on the best answer.
Code, for programmersGreedy change
function greedyChange(coins, amount) {
const sorted = [...coins].sort((a, b) => b - a); // biggest first
const taken = [];
for (const c of sorted) {
while (amount >= c) { taken.push(c); amount -= c; }
}
return taken;
}
greedyChange([100, 200, 500, 1000], 1800); // [1000, 500, 200, 100] fewest
greedyChange([1, 3, 4], 6); // [4, 1, 1] but [3, 3] is betterWhen greedy can be trusted
Greedy is correct when you can explain why the best choice now never hurts the steps after it. Some proven examples:
- Most meetings in one room: always pick the meeting that ends earliest.
- Dijkstra (Module 8): always process the nearest place not yet visited.
- Huffman coding, the basis of ZIP compression: always merge the two rarest symbols.
If you can't explain why, look for a small example that breaks it, like the 1, 3, 4 coins. If you find one, you need dynamic programming (Module 9), which tries every possibility efficiently.
Quiz
What marks a greedy algorithm?
Coins 1, 5, 6 and change of 10. What does greedy give, and is it optimal?
Greedy fails for a problem. What is the usual approach instead?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.