Skip to content

Greedy change-making

planning ahead

Level 2 of 3

Also called Biggest coin first and The cashier's algorithm.

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.

holdagainst what is leftfitscoins so far
1015yes, take it1
105no1
75no1
15, 4, 3, 2, 1yes, 5 times6
10no6
Greedy on the till. 9 comparisons: 6 that fit, one for each coin taken, and 3 that do not, one for each kind.
ways0 of 71 of 72 of 7
0 of 101593
1 of 106--
Every way to pay 15, counted in coins, 1s paying the rest. A dash pays too much. Greedy took 1 of 10 and 0 of 7: 6 coins. The fewest is 3.
The till where greedy pays double: 8 moments of its 16 steps, the steps between them left for the watch page
  1. step 1 of 16

    0×71×72×70×101×10

    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.

    watch from here

  2. step 2 of 16

    0×71×72×70×101×10

    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.

    watch from here

  3. step 3 of 16

    0×71×72×70×101×10

    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.

    watch from here

  4. step 5 of 16

    0×71×72×70×101×10

    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.

    watch from here

  5. step 10 of 16

    0×71×72×70×101×10

    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.

    watch from here

  6. step 11 of 16

    0×71×72×70×101×106

    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.

    watch from here

  7. step 14 of 16

    0×71×72×70×101×1015936

    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

    watch from here

  8. step 16 of 16

    0×71×72×70×101×1015936

    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

    watch from here

the steps, in plain words
  1. start with the whole amount left, the coins biggest firstPython lines 9, 10 and 11
  2. if the coin fits in what is left, take it, and take it off what is leftPython lines 12, 13, 14 and 15
  3. if it does not fit, go on to the next smaller coinPython line 16
  4. greedy's coins are paid: write how many where its way sitsPython line 17
  5. 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
  6. 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 nn, 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 n+3n + 3 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

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, 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
what a dearest row costs, at a billion coins held against what is left a second
nncoins held against what is lefttime
1,0001,003about 1 microsecond
100,000100,003about 100 microseconds
10,000,00010,000,003about 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, n+3n + 3: 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta coin worth the whole amount, and 1: for 9, coins of 9 and 1worsttwo coins too big to fit, and 1: for 9, coins of 11, 10 and 1
coins held against what is left33, from 1 upn+3n + 3, from 1 up
how the coins held against what is left grow in each case
tight, Θ\ThetaΘ(1)\Theta(1)Θ(n)\Theta(n)
ceiling, OOO(1)O(1)O(n)O(n)
floor, Ω\OmegaΩ(1)\Omega(1)Ω(n)\Omega(n)

extra memory: the coins taken, up to nn, 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 withgreedy takescoins takenkindscomparisons
9 and 19123
11, 10 and 1nine 1s9312
The cheapest and the dearest coins for 9, counted by the run. Coins taken plus kinds is the count.
ncheapestdearest
134
9312
1003103
1,00031,003
Comparisons on the cheapest and the dearest coins for nn, counted by the run. One stays put; the other grows with nn.

where the formula comes from

Three questions, each worked line by line. Questions 1 and 2 are the counts the plot draws.

Question 1: at most how many comparisons, CC, can greedy make paying nn, from 1 up?
  1. the move: one for each coin taken

    the line:
    one comparison foreach coin taken\begin{gathered} \text{one comparison for} \\ \text{each coin taken} \end{gathered}

    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.

  2. the move: one for each kind

    the line:
    one more for eachkind of coin\begin{gathered} \text{one more for each} \\ \text{kind of coin} \end{gathered}

    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.

  3. the move: coins taken

    the line:
    coins taken:at most n\begin{gathered} \text{coins taken:} \\ \text{at most } n \end{gathered}

    why it is allowed: The coins taken add up to nn, and each is worth 1 or more. So there are at most nn of them.

  4. the move: kinds

    the line:
    kinds of coin:at most 3\begin{gathered} \text{kinds of coin:} \\ \text{at most 3} \end{gathered}

    why it is allowed: The coins come in 2 or 3 kinds, one of them 1.

  5. the move: the dearest coins reach both

    the line:
    on 1, n+1 and n+2:every coin a 1\begin{gathered} \text{on 1, } n + 1 \text{ and } n + 2\text{:} \\ \text{every coin a 1} \end{gathered}
    holdagainst what is leftfits
    64no
    54no
    14, 3, 2, 1yes, 4 times
    10no
    Paying 4 with 6, 5 and 1. 4 coins taken and 3 kinds: 7 comparisons.

    why it is allowed: Neither big coin fits in nn, so greedy pays it all in 1s, nn coins, with 3 kinds. Lines 3 and 4 are both reached.

  6. the move: add them

    the line:
    C=n+3C = n + 3

    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.

  7. the move: a ceiling

    the line:
    C≤4nC \le 4n

    why it is allowed: From 1 up, 3 is at most 3n3n, so n+3n + 3 is at most 4n4n. For 4, 7 is at most 16.

  8. the move: read the bound

    the line:
    C∈O(n)C \in O(n)

    why it is allowed: By line 7, with the fixed multiple 4. ∈\in reads is in, and O(n)O(n) means at most a fixed multiple of nn, from some nn on.

  9. the move: a floor

    the line:
    C≥nC \ge n

    why it is allowed: n+3n + 3 is more than nn. For 4, 7 is at least 4.

  10. the move: read the bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    why it is allowed: By line 9, with the fixed multiple 1. Ω(n)\Omega(n) means at least a fixed multiple of nn, above 0, from some nn on.

  11. the move: both together

    the line:
    C∈Θ(n)C \in \Theta(n)

    why it is allowed: Lines 8 and 10 bound CC by the same growth. Θ(n)\Theta(n) means both.

try it with a small nn: at n=4n = 4, line 6 gives C=7C = 7, which you can work out by hand

Question 2: at least how many comparisons, BB, does greedy make paying nn, from 1 up?
  1. the move: at least one coin

    the line:
    coins taken: at least 1\text{coins taken: at least 1}

    why it is allowed: nn is 1 or more, so something is paid, and each coin taken costs one comparison (question 1, line 1).

  2. the move: at least two kinds

    the line:
    kinds of coin: at least 2\text{kinds of coin: at least 2}

    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).

  3. the move: the cheapest coins reach both

    the line:
    on 1 and n:one coin, two kinds\begin{gathered} \text{on 1 and } n\text{:} \\ \text{one coin, two kinds} \end{gathered}
    holdagainst what is leftfits
    44yes, take it
    40no
    10no
    Paying 4 with 4 and 1. 3 comparisons, as for any amount.

    why it is allowed: The coin nn fits, so greedy takes it, and nothing is left. Then nn and 1 each do not fit, once. For 1, a coin of nn 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.

  4. the move: add them

    the line:
    B=3B = 3

    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.

  5. the move: a ceiling

    the line:
    B≤3B \le 3

    why it is allowed: By line 4. An equals gives a ceiling and a floor at once.

  6. the move: read the bound

    the line:
    B∈O(1)B \in O(1)

    why it is allowed: By line 5, with the fixed multiple 3, whatever nn is.

  7. the move: a floor

    the line:
    B≥3B \ge 3

    why it is allowed: By line 4 again.

  8. the move: read the bound

    the line:
    B∈Ω(1)B \in \Omega(1)

    why it is allowed: By line 7, with the fixed multiple 3.

  9. the move: both together

    the line:
    B∈Θ(1)B \in \Theta(1)

    why it is allowed: Lines 6 and 8 bound BB by the same growth, 1, which is to say none.

try it with a small nn: at n=4n = 4, line 4 gives B=3B = 3, which you can work out by hand

Question 3: with coins of 1 and one other, cc, why is greedy always the fewest? Then, with 1 and 2, how few coins, FF, pay nn? And why can three kinds lose?
  1. the move: a way is fixed by one count

    the line:
    take j coins of c,and 1s for the rest\begin{gathered} \text{take } j \text{ coins of } c\text{,} \\ \text{and 1s for the rest} \end{gathered}

    why it is allowed: A way pays jj coins of cc, and the rest in 1s. The rest is nn less jj times cc.

  2. the move: count its coins

    the line:
    coins: j+(n−jc)\text{coins: } j + (n - jc)

    why it is allowed: jj coins of cc, and one coin of 1 for each 1 of the rest (line 1).

  3. the move: gather the j's

    the line:
    coins: n−(c−1)j\text{coins: } n - (c - 1)j
    coins of 4the rest in 1scoins
    01010
    167
    224
    Paying 10 with 4 and 1. Each 4 more is 3 coins fewer.

    why it is allowed: Each coin of cc is one coin but takes cc 1s away, so it saves c−1c - 1 coins, and jj of them save (c−1)j(c - 1)j. Paying 10 with 4 and 1, 0, 1 or 2 fours take 10, 7 and 4 coins.

  4. the move: more of c, fewer coins

    the line:
    the most cs that fitgive the fewest\begin{gathered} \text{the most } c\text{s that fit} \\ \text{give the fewest} \end{gathered}

    why it is allowed: By line 3, as cc is 2 or more, each coin of cc more makes the way fewer coins.

  5. the move: greedy takes the most

    the line:
    greedy takes as manycs as fit\begin{gathered} \text{greedy takes as many} \\ c\text{s as fit} \end{gathered}

    why it is allowed: It holds cc again and again until it does not fit, so one more cc would pay more than nn. No way has more ccs, and by line 4 greedy's is the fewest.

  6. the move: the most 2s

    the line:
    with 1 and 2: half of nin 2s, rounded down\begin{gathered} \text{with 1 and 2: half of } n \\ \text{in 2s, rounded down} \end{gathered}

    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.

  7. the move: the fewest

    the line:
    F=⌈n2⌉F = \lceil \frac{n}{2} \rceil

    why it is allowed: By line 5, greedy's coins are the fewest. Line 6's 2s, and one 1 when nn is odd, make half of nn rounded up. For 7, 3 + 1, which is 4.

  8. the move: three kinds can lose

    the line:
    on three kinds, more of thebiggest can be more coins\begin{gathered} \text{on three kinds, more of the} \\ \text{biggest can be more coins} \end{gathered}

    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.

try it with a small nn: at n=4n = 4, line 7 gives F=2F = 2, 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.

6, 5, 1; 4, every step written down
stepwhat happenscoins held against what is leftways tried
1Pay 4 with coins of 6, 5 and 1, taking the biggest coin that fits, again and again. All 4 is left to pay.00
2A coin of 6 does not fit in the 4 left, so go on to the next smaller coin.10
3A coin of 5 does not fit in the 4 left, so go on to the next smaller coin.20
4A coin of 1 fits in the 4 left, so take it. 3 left to pay.30
5A coin of 1 fits in the 3 left, so take it. 2 left to pay.40
6A coin of 1 fits in the 2 left, so take it. 1 left to pay.50
7A coin of 1 fits in the 1 left, so take it. 0 left to pay.60
8Nothing is left to pay, so a coin of 1 does not fit.70
9Greedy pays 4 coins: 1, 1, 1 and 1. Write 4 where its way sits in the grid.70
10Now try every way. First, nothing but 1s: 4 coins, the fewest so far.71
11Done: no way takes fewer than greedy's 4 coins, 1, 1, 1 and 1, so here the biggest coin first was the fewest.71

In all, 7 coins held against what is left. The formula from section 4, n+3n + 3, gives C=7C = 7 at n=4n = 4: 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 nn times nn, 27 for 15, 884 for 100. Greedy makes at most n+3n + 3 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 nn, as its page shows.

ways0 of 21 of 22 of 23 of 2
0 of 36543
1 of 343--
2 of 32---
Every way to pay 6 with 1, 2 and 3, counted in coins. 7 ways, in a triangle; a dash pays too much.
payways with 1, 2 and 3greedy's comparisons on 1, 2 and 3
15278
10088437
1,00083,834337
A way and a comparison are different steps, so compare how each grows, not one number with the other.

race them on one row of your own