Greedy change-making
how it works
The idea on the watch page's first example, then the whole method on it, step by step.
You owe 15, and the till holds coins of 10, 7 and 1. Take the biggest coin that fits, again and again. 10 fits, so take it: 5 is left. 10 and 7 do not fit in 5, so take 1s until nothing is left. That is 10 and five 1s, six coins. But 7, 7 and 1 is three coins. Greedy never looks back, so it never sees that taking the 10 was the mistake. The second table tries every way: a way is fixed by how many 10s and 7s it takes, with 1s for the rest. This page counts comparisons: each time a coin is held against what is left. Each coin taken costs one, and each kind of coin one more, where it stops fitting. Here 6 coins and 3 kinds: 9, as the watch page counts. Trying every way only checks greedy's answer: the page counts greedy's comparisons alone, and section 7 counts the ways. The code below pays the greedy way, tries every way, and returns both.
| hold | against what is left | fits | coins so far |
|---|---|---|---|
| 10 | 15 | yes, take it | 1 |
| 10 | 5 | no | 1 |
| 7 | 5 | no | 1 |
| 1 | 5, 4, 3, 2, 1 | yes, 5 times | 6 |
| 1 | 0 | no | 6 |
| ways | 0 of 7 | 1 of 7 | 2 of 7 |
|---|---|---|---|
| 0 of 10 | 15 | 9 | 3 |
| 1 of 10 | 6 | - | - |
step 1 of 16
Pay 15 with coins of 10, 7 and 1, taking the biggest coin that fits, again and again. All 15 is left to pay.
what it remembers to know where it is
- left to pay
- 15
- greedy's coins
- not yet
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 16
A coin of 10 fits in the 15 left, so take it. 5 left to pay.
what it remembers to know where it is
- left to pay
- 5
- greedy's coins
- 1
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 3 of 16
A coin of 10 does not fit in the 5 left, so go on to the next smaller coin.
what it remembers to know where it is
- left to pay
- 5
- greedy's coins
- 1
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 5 of 16
A coin of 1 fits in the 5 left, so take it. 4 left to pay.
what it remembers to know where it is
- left to pay
- 4
- greedy's coins
- 2
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 10 of 16
Nothing is left to pay, so a coin of 1 does not fit.
what it remembers to know where it is
- left to pay
- 0
- greedy's coins
- 6
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 11 of 16
Greedy pays 6 coins: 10, 1, 1, 1, 1 and 1. Write 6 where its way sits in the grid.
what it remembers to know where it is
- left to pay
- 0
- greedy's coins
- 6
- fewest so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 14 of 16
0 of 10 and 2 of 7 leave 1 to pay in 1s: 3 coins in all, fewer than any way before. Keep it.
what it remembers to know where it is
- left to pay
- 0
- greedy's coins
- 6
- fewest so far
- 3
step 16 of 16
Done: greedy pays 6 coins, 10, 1, 1, 1, 1 and 1, but 3 are enough. Taking the biggest coin first is not always the fewest.
what it remembers to know where it is
- left to pay
- 0
- greedy's coins
- 6
- fewest so far
- 3
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with the whole amount left, the coins biggest firstPython lines 9, 10 and 11
- if the coin fits in what is left, take it, and take it off what is leftPython lines 12, 13, 14 and 15
- if it does not fit, go on to the next smaller coinPython line 16
- greedy's coins are paid: write how many where its way sitsPython line 17
- try every way, each count of the bigger coins with the rest in 1s, and keep the fewestPython lines 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 and 28
- compare greedy's coins with the fewestPython line 29
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 greedy_coin_change(coins, amount):
"""Pay an amount taking the biggest coin that fits, again and again,
then try every way of paying it and find the fewest coins.
coins is 2 or 3 different whole numbers, one of them 1; amount is a
whole number from 1 up. Returns greedy's coins, biggest first, the
fewest coins any way takes, and whether greedy took the fewest.
"""
coins = sorted(coins, reverse=True) # biggest first
paid = [] # greedy's coins
total = 0 # what greedy has paid; amount - total is left
for coin in coins: # each coin, biggest first
while total + coin <= amount: # it fits in what is left
paid.append(coin) # take it
total += coin
# it does not fit: go on to the next smaller coin
greedy = len(paid) # how many coins greedy pays
others = [c for c in coins if c != 1] # the coins besides 1
big = others[0] if len(others) == 2 else 0 # none with two kinds
mid = others[-1]
ways = [] # how many coins each way takes
for i in range(amount // big + 1 if big else 1): # each count of big
for j in range(amount // mid + 1): # each count of mid
ones = amount - i * big - j * mid # the rest, in 1s
if ones < 0: # this way pays too much
break
ways.append(i + j + ones)
fewest = min(ways) # the fewest coins any way takes
return paid, fewest, greedy == fewest
how it scales
The plot counts the comparisons for an amount , measured from 10 to 100,000. Two cases, cheap or dear in comparisons, not in money: the cheapest coins cost greedy the fewest, the dearest the most, both drawn in section 3.
Each mark across or up is ten times the one before. The dearest line climbs one mark up for each mark across: 103 comparisons at 100, 1,003 at 1,000. Ten times the amount gives about ten times the comparisons, as the 3 of section 4's matters less and less: a slope of 1. The cheapest stays flat at 3, a slope of 0, whatever the amount.
coins held against what is left, ten times more at each mark up
, the amount to pay, ten times more at each mark to the right
- two coins too big to fit, and 1: for 9, coins of 11, 10 and 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- a coin worth the whole amount, and 1: for 9, coins of 9 and 1solid where measured by running it; dashed where its formula carries it on to ten million
| coins held against what is left | time | |
|---|---|---|
| 1,000 | 1,003 | about 1 microsecond |
| 100,000 | 100,003 | about 100 microseconds |
| 10,000,000 | 10,000,003 | about 10 milliseconds |
The coins held against what is left 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 greedy change-making's comparisons yourself, as the plot on this
page does.
Run it with Python 3.12 or later. For each amount n from 10 to 100,000
it prints the comparisons greedy makes on the cheapest coins and on the
dearest: one each time a coin is held against what is left. The counts
are the same on any computer; only the time differs.
"""
def greedy_coin_change(coins, amount):
"""Pay an amount taking the biggest coin that fits, again and again,
then try every way of paying it and find the fewest coins.
coins is 2 or 3 different whole numbers, one of them 1; amount is a
whole number from 1 up. Returns greedy's coins, biggest first, the
fewest coins any way takes, and whether greedy took the fewest.
"""
coins = sorted(coins, reverse=True) # biggest first
paid = [] # greedy's coins
total = 0 # what greedy has paid; amount - total is left
for coin in coins: # each coin, biggest first
while total + coin <= amount: # it fits in what is left
paid.append(coin) # take it
total += coin
# it does not fit: go on to the next smaller coin
greedy = len(paid) # how many coins greedy pays
others = [c for c in coins if c != 1] # the coins besides 1
big = others[0] if len(others) == 2 else 0 # none with two kinds
mid = others[-1]
ways = [] # how many coins each way takes
for i in range(amount // big + 1 if big else 1): # each count of big
for j in range(amount // mid + 1): # each count of mid
ones = amount - i * big - j * mid # the rest, in 1s
if ones < 0: # this way pays too much
break
ways.append(i + j + ones)
fewest = min(ways) # the fewest coins any way takes
return paid, fewest, greedy == fewest
def count(coins, amount):
"""How many comparisons greedy makes paying amount with these coins:
each coin, biggest first, held against what is left until it does
not fit, so one for each coin taken and one for each kind."""
comparisons = 0
total = 0
for coin in sorted(coins, reverse=True): # biggest first
while True:
comparisons += 1 # hold the coin against what is left
if total + coin > amount: # it does not fit: the next coin
break
total += coin # it fits: take it
return comparisons
def cheapest(amount):
"""A coin worth the whole amount, and 1: one coin pays it all. For
1, coins of 2 and 1."""
return ([2, 1] if amount == 1 else [amount, 1]), amount
def dearest(amount):
"""Two coins too big to fit, and 1: every coin paid is a 1."""
return [amount + 2, amount + 1, 1], amount
if __name__ == "__main__":
print(f"{'n':>7} {'cheapest':>9} {'dearest':>9}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
print(f"{n:>7} {count(*cheapest(n)):>9} {count(*dearest(n)):>9}")
best, worst and average
The cheapest coins are two kinds paying with one coin; the dearest are three kinds paying everything in 1s. Other coins cost between the two, so the average depends on which coins are chosen.
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. On the dearest coins, : at 1,000 it is 1,000 and 3, and the 3 hardly matters. So how a cost grows is what tells one method from another, and the bounds keep just that.
| besta coin worth the whole amount, and 1: for 9, coins of 9 and 1 | worsttwo coins too big to fit, and 1: for 9, coins of 11, 10 and 1 | |
|---|---|---|
| coins held against what is left | , from 1 up | , from 1 up |
| how the coins held against what is left grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: the coins taken, up to , and a count for every way tried
Extra memory is the room it needs on top of the input itself, while it runs.
| pay 9 with | greedy takes | coins taken | kinds | comparisons |
|---|---|---|---|---|
| 9 and 1 | 9 | 1 | 2 | 3 |
| 11, 10 and 1 | nine 1s | 9 | 3 | 12 |
| n | cheapest | dearest |
|---|---|---|
| 1 | 3 | 4 |
| 9 | 3 | 12 |
| 100 | 3 | 103 |
| 1,000 | 3 | 1,003 |
where the formula comes from
Three questions, each worked line by line. Questions 1 and 2 are the counts the plot draws.
the move: one for each coin taken
the line:why it is allowed: A coin is taken only after it is held against what is left and fits. On the till, 6 coins, 6 that fit.
the move: one for each kind
the line:why it is allowed: Greedy holds a coin again and again until it does not fit, once, then goes on to the next. On the till, 3 kinds, 3 that do not fit.
guess it, thenthe move: coins taken
the line:why it is allowed: The coins taken add up to , and each is worth 1 or more. So there are at most of them.
guess it, thenthe move: kinds
the line:why it is allowed: The coins come in 2 or 3 kinds, one of them 1.
guess it, thenthe move: the dearest coins reach both
the line:hold against what is left fits 6 4 no 5 4 no 1 4, 3, 2, 1 yes, 4 times 1 0 no Paying 4 with 6, 5 and 1. 4 coins taken and 3 kinds: 7 comparisons. why it is allowed: Neither big coin fits in , so greedy pays it all in 1s, coins, with 3 kinds. Lines 3 and 4 are both reached.
guess it, thenthe move: add them
the line:why it is allowed: By lines 1 to 5, the most coins taken and the most kinds, which the dearest coins make. For 4, 4 + 3, which is 7.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, 3 is at most , so is at most . For 4, 7 is at most 16.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 7, with the fixed multiple 4. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: is more than . For 4, 7 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. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 8 and 10 bound by the same growth. means both.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: at least one coin
the line:why it is allowed: is 1 or more, so something is paid, and each coin taken costs one comparison (question 1, line 1).
the move: at least two kinds
the line:why it is allowed: The coins come in 2 or 3 kinds, and each costs one comparison where it stops fitting (question 1, line 2).
guess it, thenthe move: the cheapest coins reach both
the line:hold against what is left fits 4 4 yes, take it 4 0 no 1 0 no Paying 4 with 4 and 1. 3 comparisons, as for any amount. why it is allowed: The coin fits, so greedy takes it, and nothing is left. Then and 1 each do not fit, once. For 1, a coin of would be 1 itself, so use coins 2 and 1. 2 does not fit, the 1 is taken, then 1 does not fit, still 3.
guess it, thenthe move: add them
the line:why it is allowed: By lines 1 to 3, one coin and two kinds, which the cheapest coins make. For 4 or for 4 million, 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4. An equals gives a ceiling and a floor at once.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 3, whatever is.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
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: both together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, 1, which is to say none.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: a way is fixed by one count
the line:why it is allowed: A way pays coins of , and the rest in 1s. The rest is less times .
the move: count its coins
the line:why it is allowed: coins of , and one coin of 1 for each 1 of the rest (line 1).
guess it, thenthe move: gather the j's
the line:coins of 4 the rest in 1s coins 0 10 10 1 6 7 2 2 4 Paying 10 with 4 and 1. Each 4 more is 3 coins fewer. why it is allowed: Each coin of is one coin but takes 1s away, so it saves coins, and of them save . Paying 10 with 4 and 1, 0, 1 or 2 fours take 10, 7 and 4 coins.
guess it, thenthe move: more of c, fewer coins
the line:why it is allowed: By line 3, as is 2 or more, each coin of more makes the way fewer coins.
guess it, thenthe move: greedy takes the most
the line:why it is allowed: It holds again and again until it does not fit, so one more would pay more than . No way has more s, and by line 4 greedy's is the fewest.
guess it, thenthe move: the most 2s
the line:why it is allowed: By line 5, greedy takes as many 2s as fit, and at most one 1 is left. For 7, three 2s and a 1.
guess it, thenthe move: the fewest
the line:why it is allowed: By line 5, greedy's coins are the fewest. Line 6's 2s, and one 1 when is odd, make half of rounded up. For 7, 3 + 1, which is 4.
guess it, thenthe move: three kinds can lose
the line:why it is allowed: On the till, one 10 leaves 5, which no 7 can help with, so 6 coins. No 10 leaves 15, and two 7s pay most of it, so 3 coins. Line 3 counts one coin against 1s only. With a 7 there too, more 10s can mean more coins.
guess it, then
try it with a small : at , line 7 gives , which you can work out by hand
count it yourself
Paying 4 with coins of 6, 5 and 1, written 6, 5, 1; 4: the coins, then the amount. Neither big coin fits, so every coin is a 1: these are the dearest coins for 4. Step by step, each comparison adds 1 to the count on its own step.
| step | what happens | coins held against what is left | ways tried |
|---|---|---|---|
| 1 | Pay 4 with coins of 6, 5 and 1, taking the biggest coin that fits, again and again. All 4 is left to pay. | 0 | 0 |
| 2 | A coin of 6 does not fit in the 4 left, so go on to the next smaller coin. | 1 | 0 |
| 3 | A coin of 5 does not fit in the 4 left, so go on to the next smaller coin. | 2 | 0 |
| 4 | A coin of 1 fits in the 4 left, so take it. 3 left to pay. | 3 | 0 |
| 5 | A coin of 1 fits in the 3 left, so take it. 2 left to pay. | 4 | 0 |
| 6 | A coin of 1 fits in the 2 left, so take it. 1 left to pay. | 5 | 0 |
| 7 | A coin of 1 fits in the 1 left, so take it. 0 left to pay. | 6 | 0 |
| 8 | Nothing is left to pay, so a coin of 1 does not fit. | 7 | 0 |
| 9 | Greedy pays 4 coins: 1, 1, 1 and 1. Write 4 where its way sits in the grid. | 7 | 0 |
| 10 | Now try every way. First, nothing but 1s: 4 coins, the fewest so far. | 7 | 1 |
| 11 | Done: no way takes fewer than greedy's 4 coins, 1, 1, 1 and 1, so here the biggest coin first was the fewest. | 7 | 1 |
In all, 7 coins held against what is left. The formula from section 4, , gives at : the same.
where you meet it
Greedy is how change is given by hand, and it is right on coins chosen for it.
The coins in your pocket
Australian coins are 5, 10, 20 and 50 cents, 1 dollar and 2 dollars. On them greedy gives the fewest coins for every amount they can pay. The books checked every 5 cents up to 20 dollars, so a shop can hand over change the quick way.
source: the books' volume three, chapter 30
United States coins
Cormen and others' textbook asks you to prove that greedy is the fewest on United States coins: 25, 10, 5 and 1 cents.
source: T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 3rd edition, MIT Press, 2009, problem 16-1
Checking a set of coins
Is greedy right on a new set of coins? Kozen and Zaks proved that if it ever loses, it loses on an amount below the two biggest coins added together. So a few amounts are enough to check.
source: D. Kozen and S. Zaks, Optimal bounds for the change-making problem, Theoretical Computer Science 123, 1994
what is used instead
On coins not chosen for it, the coin change table finds the fewest for every amount up to the one owed. It makes one try for each coin that fits, at each amount.
how it compares
Trying every way finds the fewest, but there are many ways. With coins 1, 2 and 3 the ways form a triangle, as the first table shows for 6: each 3 more leaves less room for 2s. Double the amount and the triangle is twice as wide and twice as tall. So it holds about four times as many ways: they grow like times , 27 for 15, 884 for 100. Greedy makes at most comparisons, and on 1, 2 and 3 far fewer: 8 for 15. The coin change table tries at most 3 coins at each amount, so it finds the fewest in time that grows like , as its page shows.
| ways | 0 of 2 | 1 of 2 | 2 of 2 | 3 of 2 |
|---|---|---|---|---|
| 0 of 3 | 6 | 5 | 4 | 3 |
| 1 of 3 | 4 | 3 | - | - |
| 2 of 3 | 2 | - | - | - |
| pay | ways with 1, 2 and 3 | greedy's comparisons on 1, 2 and 3 |
|---|---|---|
| 15 | 27 | 8 |
| 100 | 884 | 37 |
| 1,000 | 83,834 | 337 |