Greedy Algorithms: The Best-Looking Choice, Right Now
Kate owes Tom 28 cents from a till of 10, 5, 2 and 1. Like any cashier she grabs the biggest coin that fits, again and again: that's a greedy algorithm. Fast and right for normal coins, but with coins of 4, 3 and 1 it hands out three coins where two would do.
What you will learn
- Explain the greedy rule: take the best-looking choice now and never go back
- Write a greedy coin-change function and trace it by hand
- Show with the 4, 3, 1 coins why greedy can miss the best answer
- Know when greedy is safe and name problems where it is proven to work
Before you start
- Python loops and lists
- Big-O notation
Kate works at a cafe till. Tom buys a juice for 72 cents and pays with 100, so Kate owes him 28 cents. The till has coins of 10, 5, 2 and 1. Which coins make 28 cents with as few coins as possible? And Kate wants it fast; there's no time to try every mix. The answer: 10, 10, 5, 2 and 1. Five coins.
Grab the biggest coin that fits
What does any cashier do? She grabs the biggest coin that fits. Ten. Then ten again. Now 8 is left. Ten doesn't fit into 8 any more, so she moves to the next coin, five. Now 3 is left. Then two, then one, and nothing is left. Five coins in Tom's hand.
That's the greedy rule: take the best-looking choice right now, and never go back to change it. One quick choice at a time, with no looking back.
Greedy change in Python
def give_change(amount, coins):
change = [] # coins we hand out
for coin in coins: # biggest coin first
while amount >= coin: # does it still fit?
change.append(coin) # take it
amount -= coin
return change
The loop goes over the coin sizes, biggest first. While the coin still fits, take it and reduce what's left. The function never goes back to change a choice.
from greedy import give_change
coins = [10, 5, 2, 1] # biggest first
amount = 28 # Tom's change
change = give_change(amount, coins)
print("Change for " + str(amount) + ": " + str(change))
print("Coins used: " + str(len(change)))
Change for 28: [10, 10, 5, 2, 1]
Coins used: 5
The coins must be listed biggest first. That order is what makes it greedy.
Step by step
| Left to give | Coin tried | Fits? | Action |
|---|---|---|---|
| 28 | 10 | yes | take, 18 left |
| 18 | 10 | yes | take, 8 left |
| 8 | 10 | no | move on |
| 8 | 5 | yes | take, 3 left |
| 3 | 5 | no | move on |
| 3 | 2 | yes | take, 1 left |
| 1 | 2 | no | move on |
| 1 | 1 | yes | take, 0 left, done |
Each coin size is looked at once, and no choice is ever changed.
A full till
from greedy import give_change
till = [200, 100, 50, 20, 10, 5, 2, 1] # 8 coin sizes
amounts = [28, 999, 99_999]
for amount in amounts:
used = len(give_change(amount, till))
print(f"{amount:6,d} cents: {used} coins")
28 cents: 4 coins
999 cents: 11 coins
99,999 cents: 506 coins
99,999 cents in 506 coins, picked in one pass. That's about a hundred times more money than 999 cents, but only 46 times more coins, because 499 of those coins are the biggest coin, the 200. The loop hands out one coin per round and never tries another mix, which is why greedy is so fast.
Breaking it: a strange set of coins
from greedy import give_change
coins = [4, 3, 1] # a strange set of coins
amount = 6
change = give_change(amount, coins)
print("Change for " + str(amount) + ": " + str(change))
print("Coins used: " + str(len(change)))
Change for 6: [4, 1, 1]
Coins used: 3
Greedy grabs 4 first because it's the biggest coin that fits. Then only 2 is left: 4 doesn't fit, 3 doesn't fit, so it takes 1 and 1. Three coins. But 3 plus 3 is also 6, with two coins. Greedy never tried it, because it had already taken the 4 and can't undo a choice. The best-looking choice right now is not always the best in the end.
When can you trust greedy?
With 10, 5, 2 and 1, take the 10: you could swap it for 5 and 5, but that's two coins instead of one. Any swap uses the same number of coins or more, so grabbing the biggest first can never hurt. The lesson also checked every amount up to 300, and greedy always gave the fewest coins. With 4, 3 and 1, the big coin is a trap. So before you trust greedy, ask one question: could a smaller first choice ever win? When it can, you need a method that compares choices, such as dynamic programming.
What it costs
c is the number of coins handed out.
| Till | Speed | Fewest coins? |
|---|---|---|
| 10, 5, 2, 1 | O(c), one round per coin plus one check per coin size | yes |
| Full till, 200 down to 1 | O(c) | yes |
| 4, 3, 1 | O(c) | no, not always |
Where you meet greedy
- Making files smaller: zip-style codes join the two rarest letters first, again and again.
- Shortest routes: a map app keeps picking the closest place it hasn't visited yet.
- Booking meeting rooms: pick the meeting that ends earliest, and more meetings fit.
- Cabling an office network: always add the cheapest cable that connects something new.
For these problems, people have proved that the greedy rule gives the best answer. For a new problem, test it before you trust it.
Try it yourself
Change the amount to 47 cents with the 10, 5, 2, 1 till, and count the coins before you run it.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
