Why does greedy coin change fail, and what fixes it?
Question
A ticket machine gives change in coins worth 1, 4 and 5. A teammate's code always takes the biggest coin that fits. For 8 it pays 5 + 1 + 1 + 1.
Write fewest_coins(coins, amount). Return the smallest number of coins that add up to amount. Each coin value can be used any number of times. If the amount can't be made, return -1. Then explain why taking the biggest coin first is wrong.
fewest_coins([1, 4, 5], 8) # 2, from 4 + 4 fewest_coins([3, 5], 9) # 3, from 3 + 3 + 3 fewest_coins([3, 5], 7) # -1 fewest_coins([1, 4, 5], 0) # 0
def fewest_coins(coins, amount): ...
Show hints (3)
- "THE LAST COIN"
The best way to make 8 ends with some last coin: 1, 4 or 5. What is left is 7, 4 or 3, and it must be made in the best way too.
- "SMALL AMOUNTS FIRST"
So solve every amount from 0 up to 8, smallest first. Each answer only needs answers for smaller amounts, which you already have.
- "THE TABLE"
Let
best[a]be the fewest coins fora. Start withbest[0] = 0and infinity elsewhere. Thenbest[a]is the smallestbest[a - coin] + 1over the coins that fit.
Show checked explanation
Taking the biggest coin first can block the best answer: for 8, greedy pays 5 + 1 + 1 + 1, four coins, but 4 + 4 needs two. Use dynamic programming instead. best[a] is the fewest coins for amount a: the smallest best[a - coin] + 1 over all coins that fit. It runs in O(amount × number of coins).
def fewest_coins(coins, amount): best = [0] + [float("inf")] * amount # best[a]: fewest coins for a for a in range(1, amount + 1): for coin in coins: if coin <= a: best[a] = min(best[a], best[a - coin] + 1) return -1 if best[amount] == float("inf") else best[amount] def greedy(coins, amount): count = 0 for coin in sorted(coins, reverse=True): count, amount = count + amount // coin, amount % coin return count if amount == 0 else -1 for coins, amount in ([1, 4, 5], 8), ([3, 5], 9), ([3, 5], 7): g, dp = greedy(coins, amount), fewest_coins(coins, amount) print(f"{amount} from {coins}: greedy {g}, best {dp}")
8 from [1, 4, 5]: greedy 4, best 2 9 from [3, 5]: greedy -1, best 3 7 from [3, 5]: greedy -1, best -1
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the table for coins 1, 4 and 5:
| amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| fewest coins | 0 | 1 | 2 | 3 | 1 | 1 | 2 | 3 | 2 |
Take amount 8. The last coin is 1, 4 or 5, so the answer is 1 plus the smallest of best[7], best[4] and best[3]: 1 + min(3, 1, 3) = 2. Greedy only tries the 5, which leaves 3, and 3 costs three more coins.
Greedy can also miss an answer. For 9 with coins 3 and 5, it takes a 5, then a 3, and has 1 left. It says "impossible", but 3 + 3 + 3 works.
Infinity marks amounts that can't be made. Infinity plus 1 is still infinity, so those amounts never win the min. If best[amount] is still infinity at the end, return -1.
There are amount + 1 cells, and each tries every coin. Time is O(amount × number of coins), and memory is O(amount).
So is greedy always wrong? No. For some coin sets, called canonical, greedy gives the fewest coins for every amount. US coins (1, 5, 10, 25 cents) and euro coins (1, 2, 5, 10, 20, 50 cents, 1 and 2 euros) are canonical. For a coin set you don't know, use the table.
Common mistakes
- Returning
best[amount]without the infinity check. For 7 with coins 3 and 5 you returninf, a float, instead of -1. - Starting every cell at 0 instead of infinity.
mincan then never go above 0, so every amount returns 0 coins, even 7 with coins 3 and 5. - Writing it as recursion with
functools.cache. With a 1 coin, amount 5000 goes 5000 levels deep, past Python's default limit of 1000, and raisesRecursionError. The loop has no such limit.
Follow-up questions
- "Count the number of ways to make the amount instead." Start with
ways[0] = 1and add instead of taking the minimum. Put coins in the outer loop and amounts in the inner loop, so each mix of coins counts once: 8 from 1, 4 and 5 has 4 ways. With the loops swapped, 4 + 1 + 1 + 1 + 1 and 1 + 4 + 1 + 1 + 1 count as different, and you get 11. - "How can you tell if greedy is safe for a coin set?" Test a short range. If the set contains a 1, Kozen and Zaks (1994) proved that greedy, if it fails at all, first fails below the sum of the two largest coins. So compare greedy with the table for those amounts only. For 1, 4 and 5, that means checking up to 8.
What a strong answer covers
Breaks greedy with a small example, then defines best[a] in plain words and builds it from smaller amounts. Starts from infinity, returns -1 when the amount can't be made, and states O(amount × number of coins). Knows that greedy is safe only for canonical coin sets.
Open in interactive practice deck →