Algorithms · Dynamic programming
Coin Change
Make an amount with the fewest coins.
The problem
You have unlimited coins of the sizes in coins. Return the fewest coins that add up to exactly amount, or -1 if it can’t be done.
fewest_coins([1, 2, 5], 11)→3fewest_coins([2], 3)→-1Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def fewest_coins(coins, amount):take the coin sizes and an amount if amount == 0:nothing left to pay return 0zero coins needed best = -1no way found yet for c in coins:try each coin as the first one if c <= amount:does it fit? rest = fewest_coins(coins, amount - c)the best way to pay what's left if rest != -1 and (best == -1 or rest + 1 < best):a new best? best = rest + 1this coin plus the rest return bestfewest coins (or -1)Now ask: what if there were a billion?
Cash registers and vending machines solve this every day, and so do cloud systems packing jobs onto machines. When the table gets too big, they switch to “good enough” answers.
Aim for O(n)🔥 boss
Think it through
Coins are 1, 3 and 4, amount 6. Always taking the biggest coin first gives 4 + 1 + 1. Is that best?
- Yes
- No: 3 + 3 is two coins
Show the answer
No: 3 + 3 is two coins. Greedy (biggest first) can be wrong. You need to consider the options, without repeating work.
If you knew the fewest coins for every smaller amount, how would you get it for 6?
- Try each coin c: 1 + fewest(6 − c), take the best
- Divide 6 by the biggest coin
Show the answer
Try each coin c: 1 + fewest(6 − c), take the best. Each amount builds on smaller ones. Fill a table from 0 up and every answer is a few lookups. That’s dynamic programming, bottom up.
Stuck? 3 nudges, smallest first
- The obvious way works out “fewest coins for 6” over and over, once for every path that reaches 6.
- Fill in a table for every amount from 0 up. Each amount only needs answers for smaller amounts.
best[a] = min(best[a], best[a - c] + 1)for each coincthat fits, forafrom 1 toamount.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def fewest_coins(coins, amount):take the coin sizes and an amount best = [0] + [float("inf")] * amountbest[a] = fewest coins for amount a (0 needs none) for a in range(1, amount + 1):fill in amounts 1, 2, 3… in order for c in coins:try each coin as the last one if c <= a:does it fit? best[a] = min(best[a], best[a - c] + 1)one coin plus the best for what's left return best[amount] if best[amount] != float("inf") else -1the answer, or -1Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.