Coin change
Level 2 of 3
Also called Change-making problem and Fewest coins, by dynamic programming.
how it works
The idea on coins of 1, 4 and 6 paying 8. Then the whole method on the watch page's first example, coins of 1, 3 and 4 paying 6. There biggest first pays 4, 1 and 1, and the table finds 3 and 3.
You owe 8. You have coins of 1, 4 and 6, as many of each as you like. Take the biggest coin first: 6, then 1 and 1, 3 coins. But 4 and 4 is 2 coins. So that quick rule can be wrong, as the page on greedy choices shows. This method is never wrong. Make a table, with a cell for each amount from 0 to 8. Each cell will hold the fewest coins that pay its amount. Cell 0 holds 0. Then fill the cells from the left. For each amount, try each coin no bigger than it. The coin leaves a smaller amount, whose cell is already filled. That many coins, plus this one, is one way to pay. Keep the fewest. For cell 8, coin 1 leaves 7, which takes 2 coins, so 3. Coin 4 leaves 4, which takes 1, so 2. Coin 6 leaves 2, which takes 2, so 3. Keep 2. If no coin fits, or every coin tried leaves an amount no coins pay, write ∞, read infinity. On coins of 4 and 6, cell 5 is ∞: coin 4 leaves 1, which no coin pays, and coin 6 is too big. The answer is the last cell. To see which coins, read back: from the last cell, pick a coin whose cell it leaves holds 1 fewer, and repeat down to cell 0. Solving each smaller problem once like this is what books call dynamic programming. This page counts tries, one for each coin tried at each amount. The code below makes the same tries, and writes None where the watch page writes ∞.
| cell | coin 1 | coin 4 | coin 6 | keep |
|---|---|---|---|---|
| 1 | 1 | - | - | 1 |
| 2 | 2 | - | - | 2 |
| 3 | 3 | - | - | 3 |
| 4 | 4 | 1 | - | 1 |
| 5 | 2 | 2 | - | 2 |
| 6 | 3 | 3 | 1 | 1 |
| 7 | 2 | 4 | 2 | 2 |
| 8 | 3 | 2 | 3 | 2 |
step 1 of 21
Make 6 from coins of 1, 3 and 4, as few as possible. 0 coins make 0.
what it remembers to know where it is
- amount
- not yet
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 7 of 21
For 3, try a coin of 3. That leaves 0, so 3 would take one coin more than 0 does: one coin.
what it remembers to know where it is
- amount
- 3
- fewest so far
- 1
step 12 of 21
The fewest for 4 is one coin, with a coin of 4. Write 1 at 4.
what it remembers to know where it is
- amount
- 4
- fewest so far
- 1
step 15 of 21
For 5, try a coin of 4. That leaves 1, so 5 would take one coin more than 1 does: 2 coins.
what it remembers to know where it is
- amount
- 5
- fewest so far
- 2
step 18 of 21
For 6, try a coin of 3. That leaves 3, so 6 would take one coin more than 3 does: 2 coins.
what it remembers to know where it is
- amount
- 6
- fewest so far
- 2
step 20 of 21
The fewest for 6 is 2 coins, with a coin of 3. Write 2 at 6.
what it remembers to know where it is
- amount
- 6
- fewest so far
- 2
step 21 of 21
Done: 6 takes 2 coins at the fewest.
what it remembers to know where it is
- amount
- not yet
- fewest so far
- 2
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- 0 coins make the amount 0Python line 7
- for each amount from 1 up, try each coin no bigger than itPython lines 8, 9, 10 and 11
- the amount that coin leaves, plus the coin: one more than that amount's answerPython lines 12, 13 and 14
- keep the fewest, and write it at the amount, or ∞ if no coin leaves an answerPython lines 15 and 16
- the answer at the amount asked for is the fewest coinsPython line 17
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def coin_change(coins, amount):
"""The fewest coins that make amount exactly, any coin used as often as needed.
coins are different whole numbers from 1 up, and amount is a whole number from 0.
Returns the fewest coins, or None when no mix of the coins makes amount.
"""
fewest = [0] + [None] * amount # cell a holds the fewest coins for a
for a in range(1, amount + 1): # each amount from 1 up, in turn
for coin in coins:
if coin > a: # too big for this amount, so not tried
continue
left = fewest[a - coin] # one try: the cell for what it leaves
if left is None: # no coins make what it leaves
continue
if fewest[a] is None or left + 1 < fewest[a]:
fewest[a] = left + 1 # one coin more, the fewest so far
return fewest[amount] # None if no mix of the coins makes it
how it scales
The plot counts the tries for each amount from 10 to 100,000, on the three kinds of coins section 3 names.
Each mark across or up is ten times the one before. The worst and the average climb one mark up for each mark across. On 1, 2 and 3 that is 297 tries at 100 and 2,997 at 1,000, about 10 times. Here the cost is the tries, and a slope of 1 means they grow as does, as section 4's question 1 derives. The best stays flat at 6 tries, however big the amount.
coins tried, ten times more at each mark up
, the amount to make, ten times more at each mark to the right
- coins of 1, 2 and 3, the three smallestsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times A, 10 times the work
- three different coins picked at random up to the amount, every set as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- coins of the amount and the two just below it, the three biggest that fitsolid where measured by running it; dashed where its formula carries it on to ten million
| coins tried | time | |
|---|---|---|
| 1,000 | 2,997 | about 3 microseconds |
| 100,000 | 299,997 | about 300 microseconds |
| 10,000,000 | 29,999,997 | about 30 milliseconds |
The coins tried are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count coin change's tries yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each amount A from 10 to 100,000 it
prints the tries on coins of 1, 2 and 3, on A - 2, A - 1 and A, and the mean
over the plot's own 20 sets of three different coins. The counts are the same
on any computer; only the time differs.
"""
import math
def coin_change(coins, amount):
"""The fewest coins that make amount exactly, any coin used as often as needed.
coins are different whole numbers from 1 up, and amount is a whole number from 0.
Returns the fewest coins, or None when no mix of the coins makes amount.
"""
fewest = [0] + [None] * amount # cell a holds the fewest coins for a
for a in range(1, amount + 1): # each amount from 1 up, in turn
for coin in coins:
if coin > a: # too big for this amount, so not tried
continue
left = fewest[a - coin] # one try: the cell for what it leaves
if left is None: # no coins make what it leaves
continue
if fewest[a] is None or left + 1 < fewest[a]:
fewest[a] = left + 1 # one coin more, the fewest so far
return fewest[amount] # None if no mix of the coins makes it
def count(coins, amount):
"""How many tries the method makes: at each amount from 1 up, one for
each coin no bigger than it."""
tries = 0
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
tries += 1
return tries
def cheapest(amount):
"""The coins that make the fewest tries: the three biggest no bigger than
the amount, or every coin up to it below 3."""
if amount < 3:
return list(range(1, amount + 1)), amount
return [amount - 2, amount - 1, amount], amount
SPREAD = (math.sqrt(5) - 1) / 2 # the golden ratio's fractional part, 0.618...
def plot_sets(amount):
"""The plot's 20 sets for the average, from 3 up: three coins a third of
the amount apart, the first at the seed times 0.618..., its whole part
dropped, so every coin up to the amount is met about as often."""
sets = []
for seed in range(1, 21):
start = (seed * SPREAD) % 1
coins = [int(((start + j / 3) % 1) * amount) + 1 for j in range(3)]
for j in (1, 2):
while coins.index(coins[j]) != j: # a rounding met another coin
coins[j] = coins[j] % amount + 1
sets.append(coins)
return sets
if __name__ == "__main__":
print(f"{'A':>7} {'1, 2, 3':>8} {'biggest':>8} {'average':>9}")
for amount in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
sets = plot_sets(amount)
mean = sum(count(coins, amount) for coins in sets) / len(sets)
print(f"{amount:>7} {count([1, 2, 3], amount):>8} {count(*cheapest(amount)):>8} {mean:>9}")
best, worst and average
Here the size is the amount, : the table has a cell for each amount from 0 to . For one amount, the coins decide the tries. The watch page's input box takes up to three coins, so this page takes three different coins, each no bigger than the amount, as a bigger coin is never tried. A coin is tried once at each amount from its own value up, so small coins cost the most tries and big ones the fewest. Every case still fills every cell; only the tries differ. In the grid, from 2 up or from 3 up means for every amount of that or more. Below 3, fewer than three different coins fit, so each case takes every coin up to the amount.
A case is one kind of input: here, which coins. A bound says how fast its cost grows as the amount grows.
The counts are in the grid. A count is often made of pieces that grow at different speeds, and as the amount grows, the fastest-growing piece swamps the rest. For example, the tries on 1, 2 and 3, : at 1,000 it is 3,000 less 3, and the 3 hardly matters. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestcoins of the amount and the two just below it, the three biggest that fit | averagethree different coins picked at random up to the amount, every set as likely | worstcoins of 1, 2 and 3, the three smallest | |
|---|---|---|---|
| coins tried | 6, from 3 up | , from 3 up | , from 2 up |
| how the coins tried grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: A table of one cell for each amount from 0 to the amount owed.
Extra memory is the room it needs on top of the input itself, while it runs.
| coin | tried at | tries |
|---|---|---|
| 1 | amounts 1 to 6 | 6 |
| 2 | amounts 2 to 6 | 5 |
| 3 | amounts 3 to 6 | 4 |
| amount | 1, 2 and 3 | three biggest | average | sets |
|---|---|---|---|---|
| 3 | 6 | 6 | 6 | 1 |
| 4 | 9 | 6 | 7.5 | 4 |
| 5 | 12 | 6 | 9 | 10 |
| 6 | 15 | 6 | 10.5 | 20 |
| 7 | 18 | 6 | 12 | 35 |
| 8 | 21 | 6 | 13.5 | 56 |
| 9 | 24 | 6 | 15 | 84 |
| digits | biggest amount | cells |
|---|---|---|
| 1 | 9 | 10 |
| 2 | 99 | 100 |
| 3 | 999 | 1,000 |
| 7 | 9,999,999 | 10,000,000 |
where the formula comes from
Five questions, each worked line by line. Question 1 is the count the plot draws.
the move: count one coin
the line:amount coins tried tries 1 1 1 2 1, 2 2 3 1, 2, 3 3 4 1, 2, 3 3 Coins of 1, 2 and 3 paying 4, 9 tries. why it is allowed: Coin is tried at each amount from up to , both ends counted, and at none below its value. For 4, coin 2 is tried at 2, 3 and 4: 4 less 2, plus 1, which is 3 times.
the move: add the three coins
the line:why it is allowed: By line 1, coin 1 is tried times, coin 2 times and coin 3 times. At 2, coin 3 is never tried, and is 0. For 4, 4 + 3 + 2, which is 9.
guess it, thenthe move: add them up
the line:why it is allowed: Three lots of , less 1 and less 2. For 4, 12 less 3, which is 9.
guess it, thenthe move: a ceiling
the line:why it is allowed: Taking 3 away leaves less. For 4, 9 is at most 12.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 3.
guess it, thenthe move: a floor
the line:why it is allowed: Take from , and 2 lots of , less 3, are left. From 2 up, that is at least 1, so is more than . For 4, 9 is at least 4.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, only a fixed multiple apart.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count each coin
the line:amount coins tried tries 2 2 1 3 2, 3 2 4 2, 3, 4 3 Coins of 2, 3 and 4 paying 4, 6 tries. Amount 1 fits no coin. why it is allowed: The three biggest are , and . By question 1's line 1, they are tried 3, 2 and 1 times. For 4, coins 2, 3 and 4.
the move: add them up
the line:why it is allowed: 3 + 2 + 1 is 6, with no in it, so the same for 4 as for 4 million.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, a fixed number of tries, whatever the amount.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same: a fixed 6 tries, no growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: line them up
the line:why it is allowed: The coins are different whole numbers, so each is at least 1 more than the one before. For 4, the sets are 1, 2, 3 and 1, 2, 4 and 1, 3, 4 and 2, 3, 4.
the move: how high each can be
the line:why it is allowed: The biggest is at most , and each coin is at least 1 below the next. For 4, the middle is at most 3 and the smallest at most 2.
guess it, thenthe move: so each is tried
the line:coin can be tried smallest 1 to 4 6 down to 3 middle 2 to 5 5 down to 2 biggest 3 to 6 4 down to 1 Three different coins up to 6. Added up, the tries run from 3 + 2 + 1, which is 6, to 6 + 5 + 4, which is 15. why it is allowed: By line 2 and question 1's line 1: the bigger a coin, the fewer times it is tried. Coin is tried once, coin twice and coin 3 times.
guess it, thenthe move: the fewest
the line:why it is allowed: By line 3, no set makes fewer, and question 2's coins make exactly that. For 4, coins 2, 3 and 4 make 6.
guess it, thenthe move: how low each can be
the line:why it is allowed: 1 is the smallest coin there is, and each coin is at least 1 more than the one before.
guess it, thenthe move: how often at most
the line:why it is allowed: By line 5 and question 1's line 1: the smaller a coin, the more times it is tried.
guess it, thenthe move: so the most
the line:why it is allowed: Line 6's tries added up are question 1's line 2, which is , and question 1's coins make exactly that. For 4, every set makes from 6 to 9.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: list the sets
the line:set coin 1 coin 2 coin 3 coin 4 tries 1, 2, 3 4 3 2 - 9 1, 2, 4 4 3 - 1 8 1, 3, 4 4 - 2 1 7 2, 3, 4 - 3 2 1 6 added up 12 9 6 3 30 The 4 sets up to 4, each coin's tries in its own column by question 1's line 1. Each column holds its coin's tries 3 times, once for each set that holds it. why it is allowed: That is what an average is when every set is as likely. For 4, there are 4 sets, and their tries add up to 30, so 7.5.
the move: each coin's share
the line:why it is allowed: is how many coins there are to pick from. Every set holds 3 of them, so the sets hold 3 times as many coins as there are sets. No coin is favoured, so each is in an equal share of the sets, 3 in every . For 4, each coin is in 3 of the 4 sets. At 5, the 10 sets hold 30 coins, 6 of each, so each coin is in 6 of the 10.
guess it, thenthe move: add by columns
the line:why it is allowed: Add line 1's grid down its columns instead of along its rows. For 4, 12 + 9 + 6 + 3, which is 30, as before.
guess it, thenthe move: divide by the sets
the line:why it is allowed: Divide by the number of sets. By lines 2 and 3, each coin's tries count 3 times for every sets, so 3 over times per set. By question 1's line 1, coins 1 to are tried , , and so on down to 1 times. For 4, 4 + 3 + 2 + 1 is 10, and 3 times 10 over 4 is 7.5. At 5, 3 times 15 over 5, which is 9.
guess it, thenthe move: pair them up
the line:why it is allowed: Pair the first number with the last, with 1, then with 2. Each pair adds to , so the numbers average half of that. An odd count's middle number is that half too: at 5, 5 + 1 and 4 + 2, and the middle 3 alone is half of 6. For 4, 4 + 1 and 3 + 2, so 10 over 4 is 2.5.
guess it, thenthe move: tidy up
the line:why it is allowed: The same, written as one fraction. For 4, 15 over 2, which is 7.5.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, is at most , and half of 3 times is . For 4, 7.5 is at most 12.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 7, with the fixed multiple 3.
guess it, thenthe move: a floor
the line:why it is allowed: By line 6, is more than half of , which is more than . For 4, 7.5 is at least 4.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 8 and 10 bound by the same growth.
guess it, then
try it on small inputs: over the 4 sets of three different coins up to 4, the average is
the move: it starts right
the line:why it is allowed: 0 coins pay 0, and nothing pays it with fewer.
the move: suppose so far
the line:Cell 8 is filled last. Cells 0 to 7 are to its left, and its 3 tries read cells 7, 4 and 2. why it is allowed: Cells fill from the left, so this cell reads only cells already filled. Suppose, for now, that each of those is right. Lines 3 to 7 show that this cell is then right too, and line 8 then covers every cell.
guess it, thenthe move: a try is a real way
the line:why it is allowed: A coin no bigger than the amount leaves a smaller amount. Pay that in the fewest coins, the number its cell holds by line 2, then add the coin. On 1, 4 and 6, cell 8's coin 4 leaves 4, paid by one 4, so 4 and 4.
guess it, thenthe move: so at most
the line:why it is allowed: Each try with a number is a way to pay, by line 3, so the fewest can be no more than any of them. For 8, the tries give 3, 2 and 3.
guess it, thenthe move: the best way is a try
the line:why it is allowed: If some way pays this amount, take a best one, and any coin in it. That coin is no bigger than the amount, so it is tried. The other coins pay what it leaves, so there are at least as many as that cell holds, by line 2. With the coin, that is at least its try. For 8, a best way is 4 and 4. The other 4 pays 4, at least cell 4's 1 coin, so at least 2, coin 4's try.
guess it, thenthe move: so the cell is right
the line:why it is allowed: By lines 4 and 5, the smallest try is exactly the fewest, and that is what the cell keeps. For 8, 2.
guess it, thenthe move: and ∞
the line:amount coin 4 coin 6 holds 1 - - ∞ 2 - - ∞ 3 - - ∞ 4 1 - 1 5 ∞ - ∞ 6 ∞ 1 1 7 ∞ ∞ ∞ 8 2 ∞ 2 Coins of 4 and 6 up to 8. A try that leaves ∞ gives ∞, and a dash is a coin too big. A cell holds ∞ when no try gives a number. why it is allowed: Any way to pay holds some coin no bigger than the amount. The rest pay what it leaves, so that cell would hold a number, and its try would too. On coins of 4 and 6, 5 is ∞, as coin 4 leaves 1, which is ∞.
guess it, thenthe move: every cell
the line:why it is allowed: By line 1, cell 0 is right. By lines 2 to 7, each later cell is right once those before it are. So, filling from the left, every cell is, the last included.
guess it, thenthe move: count them
the line:why it is allowed: One cell for each amount from 0 to , each right by line 8. For 4, 5 cells.
guess it, then
try it with a small : at , line 9 gives , which you can work out by hand
count it yourself
Coins of 1, 2 and 3 paying 4, step by step. Each try adds 1 to the count on its own step.
| step | what happens | coins tried |
|---|---|---|
| 1 | Make 4 from coins of 1, 2 and 3, as few as possible. 0 coins make 0. | 0 |
| 2 | For 1, try a coin of 1. That leaves 0, so 1 would take one coin more than 0 does: one coin. | 1 |
| 3 | The fewest for 1 is one coin, with a coin of 1. Write 1 at 1. | 1 |
| 4 | For 2, try a coin of 1. That leaves 1, so 2 would take one coin more than 1 does: 2 coins. | 2 |
| 5 | For 2, try a coin of 2. That leaves 0, so 2 would take one coin more than 0 does: one coin. | 3 |
| 6 | The fewest for 2 is one coin, with a coin of 2. Write 1 at 2. | 3 |
| 7 | For 3, try a coin of 1. That leaves 2, so 3 would take one coin more than 2 does: 2 coins. | 4 |
| 8 | For 3, try a coin of 2. That leaves 1, so 3 would take one coin more than 1 does: 2 coins. | 5 |
| 9 | For 3, try a coin of 3. That leaves 0, so 3 would take one coin more than 0 does: one coin. | 6 |
| 10 | The fewest for 3 is one coin, with a coin of 3. Write 1 at 3. | 6 |
| 11 | For 4, try a coin of 1. That leaves 3, so 4 would take one coin more than 3 does: 2 coins. | 7 |
| 12 | For 4, try a coin of 2. That leaves 2, so 4 would take one coin more than 2 does: 2 coins. | 8 |
| 13 | For 4, try a coin of 3. That leaves 1, so 4 would take one coin more than 1 does: 2 coins. | 9 |
| 14 | The fewest for 4 is 2 coins, with a coin of 1. Write 2 at 4. | 9 |
| 15 | Done: 4 takes 2 coins at the fewest. | 9 |
In all, 9 coins tried. The formula from section 4, , gives at : the same.
where you meet it
The table checks a set of coins, and helps choose one.
Is biggest first safe for these coins?
Dexter Kozen and Shmuel Zaks showed this in a paper published in 1994. For a set of coins with a coin of 1, if biggest coin first is ever wrong, it is already wrong below the two biggest coins added up. On 1, 4 and 6, those add up to 10, and biggest first is first wrong at 8. So one way to check a set is this table up to there, set beside biggest first.
source: D. Kozen and S. Zaks, Optimal bounds for the change-making problem (opens in a new tab), Theoretical Computer Science 123, 1994
Australian coins
On coins of 5, 10, 20 and 50 cents, 1 dollar and 2 dollars, biggest coin first is right for every amount they can pay. The books checked it on every multiple of 5 cents up to 20 dollars, 400 amounts.
source: the books' volume three, chapter 30
An 18 cent coin
Jeffrey Shallit asked which four coins make change from 0 to 99 cents in the fewest coins on average. On 1, 5, 10 and 25 cents it is 4.7. On 1, 5, 18 and 25 cents, or 1, 5, 18 and 29, it is 3.89. On 1, 5, 18 and 25, biggest first pays 36 cents as 25, 5, 5 and 1, where 18 and 18 is 2 coins. So the fewest needs a table like this one.
source: J. Shallit, What this country needs is an 18¢ piece (opens in a new tab), The Mathematical Intelligencer 25, 2003, and his preprint (opens in a new tab)
what is used instead
On coins where biggest first is safe, such as Australia's, it is quicker: a few steps, no table.
how it compares
Biggest coin first is quick, and wrong on some coins. The plain method works out an amount by asking for the fewest for each amount its coins leave. Each ask is a call, and the same amounts are worked out again and again. A memo stores each amount's answer, so a repeat asks for nothing more, as the page on solving each smaller problem once shows. The table fills every cell from the left and makes no calls.
- first time
- asked before
- first time
- asked before, answered at once
| way | coins for 20 | work for 20 |
|---|---|---|
| biggest coin first | 5 | 5 coins taken |
| plain method | 4 | 3,053 calls |
| with a memo | 4 | 53 calls |
| the table | 4 | 52 tries |