---
title: "Greedy Algorithms"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 18
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/18-greedy-algorithms
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 18 — Greedy Algorithms

A shopkeeper owes $87$ in change and has coins of $1$, $2$, $5$, $10$, $20$ and $50$. Without thinking she hands over the largest coin that fits, $50$, then again the largest that fits what is left, $20$, then $10$, $5$, $2$: five coins, and no way of giving fewer. Her rule never looks back and never looks ahead, and here it is the best possible.

Rules of this kind are called greedy. They are fast and easy to write, and they are often right, but not always: with other coins the same shopkeeper gives one coin too many. This chapter writes greedy rules for three problems, proves when they are right, and lets a program find where they go wrong.

**You already know.**

`sorted(t, key=f)` sorts by the values of `f` (chapter [7](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#ch-g10-data-tables)). The cost of an algorithm counts its [elementary operations](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#def-g11-cost-of-an-algorithm-elementary) (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)); an invariant is kept by each turn of a loop (chapter [16](https://one-course.com/books/computer-science/2/en/chapter/16-proving-algorithms-correct#ch-g11-proving-algorithms-correct)).

## 18.1 Optimisation problems

**Definition 18.1 (Optimisation problem, objective, optimal solution).**

An *optimisation problem* asks, among the feasible solutions of a problem, for one that makes a number as small or as large as possible. That number is the *objective*. A feasible solution with the best possible objective is an *optimal solution*.

For change, a feasible solution is a set of coins that adds up to the amount, and the [objective](#def-g11-greedy-algorithms-optimisation) is the number of coins, to be made as small as possible. On a small amount, a program can try every combination and keep the best. That is slow, but surely right, and it serves as a reference.

```python
"""The fewest coins by trying every combination: slow, but surely right."""
from change_greedy import greedy_change


def fewest(amount, coins):
    """Return (fewest coins, combinations tried). coins sorted, coins[0] == 1."""
    if len(coins) == 1:
        return amount, 1                  # only coins of 1 left
    *smaller, c = coins
    best, tried = None, 0
    for k in range(amount // c + 1):      # k coins of the largest value, then the rest
        n, t = fewest(amount - k * c, smaller)
        tried += t
        if best is None or k + n < best:
            best = k + n
    return best, tried


if __name__ == "__main__":
    print("20 with 1, 2, 5:", fewest(20, [1, 2, 5]))
    coins = [1, 2, 5, 10, 20, 50]
    limit = coins[-1] + coins[-2]         # 70: the theorem says this is far enough
    bad = [a for a in range(1, limit)
           if len(greedy_change(a, coins)) != fewest(a, coins)[0]]
    print(f"amounts below {limit} where greedy is not optimal: {bad}")
```

***Listing 18.1.** The fewest coins, by trying every combination. code/grade-11/07-greedy-algorithms/listings/change_exhaustive.py*

```
$ python change_exhaustive.py
20 with 1, 2, 5: (4, 29)
amounts below 70 where greedy is not optimal: []
```

***Output 18.1.** $20$ needs $4$ coins of $1$, $2$ and $5$, found among $29$ combinations; with six coins, greedy matches the fewest on every amount checked.*

## 18.2 The greedy choice

**Definition 18.2 (Greedy algorithm).**

A *greedy algorithm* builds a solution one piece at a time, each time taking the piece that looks best at that moment, by a fixed rule, and never going back on a choice.

**Method 18.3 (Designing a greedy algorithm).**

1. Choose the rule: the order in which candidates are looked at, often a sort by a well-chosen key.
2. Take each candidate that keeps the solution feasible.
3. Prove that the result is optimal, often by exchange: take any [optimal solution](#def-g11-greedy-algorithms-optimisation) , and change it, step by step, into the greedy one without making it worse.
4. If there is no proof, look for a counter-example with a program that compares greedy with an exhaustive search on small inputs.

```python
def greedy_change(amount, coins):
    """Take the largest coin that fits, again and again. coins must contain 1."""
    given = []
    for c in sorted(coins, reverse=True):
        while c <= amount:
            given.append(c)
            amount -= c
    return given


if __name__ == "__main__":
    COINS = [1, 2, 5, 10, 20, 50]
    for amount in [87, 43, 9]:
        change = greedy_change(amount, COINS)
        print(f"{amount}: {change} -> {len(change)} coins")
```

***Listing 18.2.** Greedy change: the largest coin that fits, again and again. code/grade-11/07-greedy-algorithms/listings/change_greedy.py*

```
$ python change_greedy.py
87: [50, 20, 10, 5, 2] -> 5 coins
43: [20, 20, 2, 1] -> 4 coins
9: [5, 2, 2] -> 3 coins
```

***Output 18.2.** Three amounts with the coins $1$, $2$, $5$, $10$, $20$, $50$.*

With the coins $1$, $2$, $5$ an exchange argument proves greedy right. Take a way of paying with the fewest coins. It uses at most one coin of $1$, since two could become one $2$; at most two coins of $2$, since three could become a $5$ and a $1$; and never two $2$ with a $1$, which could become a $5$. So the coins of $1$ and $2$ add up to at most $4$, and every $5$ that fits is used, exactly as greedy does; what remains, $0$ to $4$, has only one way with these rules: $0$, $1$, $2$, $2 + 1$, $2 + 2$, again greedy’s way. Greedy and an [optimal solution](#def-g11-greedy-algorithms-optimisation) are the same.

For six coins a full case argument is long. A theorem does the work instead.

**Theorem 18.4 (Kozen and Zaks).**

Let a system of coins have the values $1 = c_1 < c_2 < \dots < c_m$, with $m \ge 3$. If greedy change gives more coins than necessary for some amount, then it does so already for some amount $x$ with $c_3 + 1 < x < c_m + c_{m-1}$.

**Proof.** *Admitted at this level.* ∎

For $1$, $2$, $5$, $10$, $20$, $50$, it is enough to check every amount below $50 + 20 = 70$, which the output above did: no failure there, so none anywhere. A system for which greedy change is always optimal has a name.

**Definition 18.5 (Canonical coin system).**

A coin system is *canonical* if, for every amount, greedy change uses the fewest coins possible.

## 18.3 Choosing activities

One room, twelve requests, each a start and an end hour; two bookings that overlap cannot both be kept. The goal is to keep as many as possible. Several greedy rules come to mind: shortest first, earliest start first, earliest end first. Only the last is always right.

```python
"""One room, many requests: keep as many bookings as possible, earliest end first."""
import random

rng = random.Random(11)
requests = []
for name in "ABCDEFGHIJKL":
    start = rng.randint(8, 18)
    requests.append((name, start, start + rng.randint(1, 3)))   # hours, end excluded


def earliest_end_first(requests):
    chosen, free_from = [], 0
    for name, start, end in sorted(requests, key=lambda r: r[2]):
        if start >= free_from:            # does not overlap the last one kept
            chosen.append((name, start, end))
            free_from = end
    return chosen


for name, start, end in sorted(requests, key=lambda r: r[2]):
    print(f"{name}: {start:2}h-{end:2}h")
print("kept:", " ".join(name for name, _, _ in earliest_end_first(requests)))
```

***Listing 18.3.** Earliest end first: keep a request when it starts after the last one kept ends. code/grade-11/07-greedy-algorithms/listings/activities.py*

```
$ python activities.py
G: 10h-11h
I: 10h-11h
D: 11h-12h
B: 15h-17h
H: 15h-17h
A: 15h-18h
E: 16h-18h
C: 16h-19h
J: 16h-19h
K: 18h-19h
L: 17h-19h
F: 18h-21h
kept: G D B K
```

***Output 18.3.** The requests sorted by end hour, and the four kept.*

![The twelve requests, from the run, in order of end hour. In blue, the four that earliest end first keeps: each starts after the previous blue one ends.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-greedy-algorithms/fig-bc4841de1c4a.svg)

*The twelve requests, from the run, in order of end hour. In blue, the four that earliest end first keeps: each starts after the previous blue one ends.*

Why is it optimal? Let $g_1, g_2, \dots$ be the bookings greedy keeps, in order, and $o_1, o_2, \dots$ those of an optimal choice, in order. Greedy “stays ahead”: $g_1$ ends no later than $o_1$, since greedy took the request that ends first. If $g_k$ ends no later than $o_k$, then $o_{k+1}$, which starts after $o_k$ ends, starts after $g_k$ ends too; so it was still available to greedy, which took a request ending no later, and $g_{k+1}$ ends no later than $o_{k+1}$. Greedy can therefore never run out before the optimal choice does: it keeps at least as many bookings.

![Greedy stays ahead. Each g_k ends no later than o_k, so o_k+1 was still free for greedy, and replacing o_k by g_k in the optimal choice keeps it feasible.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-greedy-algorithms/fig-5842492c87c6.svg)

*Greedy stays ahead. Each $g_k$ ends no later than $o_k$, so $o_{k+1}$ was still free for greedy, and replacing $o_k$ by $g_k$ in the optimal choice keeps it feasible.*

## 18.4 Filling a knapsack

A trader’s sack holds $15$ kg. Goods can be cut: half a sack of rice is worth half its price. The greedy rule takes the goods in order of value per kilogram, as much as fits.

```python
"""A sack of 15 kg, goods that can be cut: take the best value per kilogram first."""
GOODS = [("tea", 4, 60), ("rice", 10, 40), ("spices", 2, 50),
         ("coffee", 6, 72), ("flour", 8, 16)]          # name, kg, value


def fill(goods, capacity):
    load, value = [], 0
    for name, kg, worth in sorted(goods, key=lambda g: g[2] / g[1], reverse=True):
        take = min(kg, capacity)          # all of it, or what still fits
        if take == 0:
            break
        load.append((name, take))
        value += worth * take / kg
        capacity -= take
    return load, value


load, value = fill(GOODS, 15)
for name, kg in load:
    print(f"{name:7} {kg} kg")
print("value:", value)
```

***Listing 18.4.** The fractional knapsack: the best value per kilogram first. code/grade-11/07-greedy-algorithms/listings/knapsack_fractional.py*

```
$ python knapsack_fractional.py
spices  2 kg
tea     4 kg
coffee  6 kg
rice    3 kg
value: 194.0
```

***Output 18.4.** Three goods whole, then $3$ kg of rice fill the sack.*

![The goods as bars, widths in kilograms, heights in value per kilogram, best first. The sack takes everything left of the line; the value is the blue area, 194.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-greedy-algorithms/fig-a5b04870f111.svg)

*The goods as bars, widths in kilograms, heights in value per kilogram, best first. The sack takes everything left of the line; the value is the blue area, $194$.*

Here greedy is optimal: any kilogram in the sack that is not among the best ones could be swapped for a better one left out, which raises the value. Now suppose the objects cannot be cut: a lamp is taken whole or not at all.

```python
"""Whole objects only: the best value per kilogram first is no longer optimal."""
from itertools import combinations

OBJECTS = [("A", 6, 30), ("B", 5, 20), ("C", 5, 20)]   # name, kg, value
CAPACITY = 10

load, kg_used = [], 0
for name, kg, _ in sorted(OBJECTS, key=lambda o: o[2] / o[1], reverse=True):
    if kg_used + kg <= CAPACITY:
        load.append(name)
        kg_used += kg
print("greedy keeps", load, "value", sum(o[2] for o in OBJECTS if o[0] in load))

best = max((sum(o[2] for o in subset), [o[0] for o in subset])
           for r in range(len(OBJECTS) + 1)
           for subset in combinations(OBJECTS, r)
           if sum(o[1] for o in subset) <= CAPACITY)
print("every subset tried: best", best[1], "value", best[0])
```

***Listing 18.5.** Whole objects: the same rule, and every subset as a reference. code/grade-11/07-greedy-algorithms/listings/knapsack_01_greedy_fails.py*

```
$ python knapsack_01_greedy_fails.py
greedy keeps ['A'] value 30
every subset tried: best ['B', 'C'] value 40
```

***Output 18.5.** The densest object takes $6$ kg of the $10$ and leaves room for nothing else.*

No greedy rule is known to solve the knapsack with whole objects; the grade-12 chapter on dynamic programming solves it exactly by a different method.

## 18.5 When greedy fails

With coins of $1$, $3$ and $4$, greedy pays $6$ as $4 + 1 + 1$, three coins, while $3 + 3$ needs two. The program below looks, among all systems of three coins up to $8$, for those that are not [canonical](#def-g11-greedy-algorithms-canonical), and for the first amount each gets wrong; the theorem says to look only below the sum of the two largest coins.

```python
"""Systems of three coins 1 < a < b <= 8 where greedy change can go wrong."""
from change_exhaustive import fewest
from change_greedy import greedy_change

for b in range(3, 9):
    for a in range(2, b):
        coins = [1, a, b]
        bad = [m for m in range(1, a + b)          # below the two largest added
               if len(greedy_change(m, coins)) > fewest(m, coins)[0]]
        if bad:
            m = bad[0]
            print(f"coins {coins}: first failure at {m}:",
                  f"greedy {greedy_change(m, coins)}, fewest {fewest(m, coins)[0]}")
```

***Listing 18.6.** Every system of three coins up to $8$ where greedy fails. code/grade-11/07-greedy-algorithms/listings/smallest_counterexample.py*

```
$ python smallest_counterexample.py
coins [1, 3, 4]: first failure at 6: greedy [4, 1, 1], fewest 2
coins [1, 4, 5]: first failure at 8: greedy [5, 1, 1, 1], fewest 2
coins [1, 4, 6]: first failure at 8: greedy [6, 1, 1], fewest 2
coins [1, 5, 6]: first failure at 10: greedy [6, 1, 1, 1, 1], fewest 2
coins [1, 5, 7]: first failure at 10: greedy [7, 1, 1, 1], fewest 2
coins [1, 6, 7]: first failure at 12: greedy [7, 1, 1, 1, 1, 1], fewest 2
coins [1, 5, 8]: first failure at 10: greedy [8, 1, 1], fewest 2
coins [1, 6, 8]: first failure at 12: greedy [8, 1, 1, 1, 1], fewest 2
coins [1, 7, 8]: first failure at 14: greedy [8, 1, 1, 1, 1, 1, 1], fewest 2
```

***Output 18.6.** The smallest system that fails is $1$, $3$, $4$, first at $6$.*

![The amount 6 with coins 1, 3, 4. Taking 4 first leaves 2, which only coins of 1 can pay.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-greedy-algorithms/fig-898c68a6c144.svg)

*The amount $6$ with coins $1$, $3$, $4$. Taking $4$ first leaves $2$, which only coins of $1$ can pay.*

## 18.6 Exercises

**Exercise 18.1 ★.**

Give greedy change for $87$ with coins $1$, $2$, $5$, $10$, $20$, $50$, without the program.

**Solution of Exercise 18.1.**

$50$ leaves $37$; $20$ leaves $17$; $10$ leaves $7$; $5$ leaves $2$; $2$ leaves $0$: five coins, $50 + 20 + 10 + 5 + 2$.

**Exercise 18.2 ★.**

With coins $1$, $3$, $4$, how many coins does greedy give for $6$? How many are needed?

**Solution of Exercise 18.2.**

Greedy gives $4 + 1 + 1$, three coins; $3 + 3$ needs two.

**Exercise 18.3 ★.**

Four requests: P from $8$h to $12$h, S from $11$h to $13$h, Q from $12$h to $16$h, R from $13$h to $14$h. Which does earliest end first keep?

**Solution of Exercise 18.3.**

By end hour: P ($12$h), S ($13$h), R ($14$h), Q ($16$h). P is kept; S starts at $11$h, before $12$h: no; R starts at $13$h: kept; Q starts at $12$h, before $14$h: no. P and R, two bookings, as many as possible.

**Exercise 18.4 ★.**

With the goods of the chapter and a sack of $8$ kg, what does the fractional greedy take, and for what value?

**Solution of Exercise 18.4.**

Spices ($2$ kg, $50$), tea ($4$ kg, $60$), then $2$ of the $6$ kg of coffee, worth $72 \times 2/6 = 24$: in all $134$.

**Exercise 18.5 ★.**

Write `greedy_change(amount, coins)` with `divmod`, one division per coin value.

**Solution of Exercise 18.5.**

    `def greedy_change(amount, coins):`

        `given = []`

        `for c in sorted(coins, reverse=True):`

            `k, amount = divmod(amount, c)`

            `given += [c] * k`

        `return given`

`divmod(a, c)` gives the number of coins `c` that fit and what is left, in one step.

**Exercise 18.6 ★★.**

A student sorts the requests by start time instead of end time. Find four requests on which this keeps one booking when three are possible.

**Solution of Exercise 18.6.**

L from $8$h to $20$h, x from $9$h to $10$h, y from $10$h to $11$h, z from $11$h to $12$h. By start, L comes first and is kept; it overlaps all the others. Earliest end first keeps x, y and z.

**Exercise 18.7 ★★.**

Write `max_activities(requests)`, each request being a triple `(name, start, end)`, that returns the names kept by earliest end first.

**Solution of Exercise 18.7.**

    `def max_activities(requests):`

        `chosen, free_from = [], 0`

        `for name, start, end in sorted(requests, key=lambda r: r[2]):`

            `if start >= free_from:`

                `chosen.append(name)`

                `free_from = end`

        `return chosen`

The tests compare its count with the best found by trying every subset, on $200$ random sets of requests. (The `0` start assumes hours are not negative.)

**Exercise 18.8 ★★.**

How many combinations does `fewest(20, [1, 2, 5])` try? Count them by hand, by the number of coins of $5$, then of $2$.

**Solution of Exercise 18.8.**

With $k$ coins of $5$, from $0$ to $4$, the rest $20 - 5k$ is paid with $1$ and $2$, trying every number of coins of $2$: $11$, $8$, $6$, $3$ and $1$ ways for $k = 0$ to $4$. In all $29$, as printed.

**Exercise 18.9 ★★.**

With a sack of $10$ kg, compare the fractional greedy by value per kilogram with a greedy that takes the most valuable goods first. Which is better here, and why?

**Solution of Exercise 18.9.**

By value per kilogram: spices, tea, and $4$ kg of coffee, $50 + 60 + 48 = 158$. By value: coffee ($72$, $6$ kg) and tea ($60$, $4$ kg), $132$. Per kilogram is better: the sack’s limit is in kilograms, and the spices, worth less in all, give the most for each kilogram they use.

**Exercise 18.10 ★★.**

Objects that cannot be cut: X of $5$ kg worth $40$, Y and Z of $4$ kg worth $28$ each; the sack holds $8$ kg. What does greedy by value per kilogram keep, and what is optimal?

**Solution of Exercise 18.10.**

Values per kilogram: X $8$, Y and Z $7$. Greedy keeps X ($5$ kg), and then neither Y nor Z fits: value $40$. Y and Z together weigh $8$ kg and are worth $56$, which is optimal.

**Exercise 18.11 ★★.**

Write `is_canonical_upto(coins, m)` that compares greedy with `fewest` on every amount from $1$ to $m$. With the theorem, which $m$ makes it a full test?

**Solution of Exercise 18.11.**

    `def is_canonical_upto(coins, m):`

        `return all(len(greedy_change(a, coins)) == fewest(a, sorted(coins))[0]`

                    `for a in range(1, m + 1))`

By the theorem, $m = c_m + c_{m-1} - 1$, the largest coin plus the next one, minus one, is enough: if no amount up to it fails, none fails at all.

**Exercise 18.12 ★★★.**

Write out in full the proof that earliest end first keeps as many bookings as possible, with the “stays ahead” statement as an invariant of its loop.

**Solution of Exercise 18.12.**

Let the requests be sorted by end hour, and let $o_1, o_2, \dots, o_p$ be an optimal choice, in order of time. Invariant of the loop: after greedy has kept $g_1, \dots, g_k$, with $k \le p$, each $g_i$ ends no later than $o_i$. It holds for $k = 0$. When greedy has $g_1, \dots, g_k$ and $k < p$, the request $o_{k+1}$ starts after $o_k$ ends, hence after $g_k$ ends: it is compatible with what greedy kept, and greedy, scanning by end hour, keeps a request no later than $o_{k+1}$ in that order, so its $g_{k+1}$ ends no later than $o_{k+1}$. The invariant is kept as long as $k < p$, so greedy keeps at least $p$ requests, and therefore exactly $p$, the most possible. The loop is a `for` over the sorted list and stops.

**Exercise 18.13 ★★★.**

Prove that greedy change is optimal for the coins $1$, $2$, $5$ by treating the amounts left after the coins of $5$: $0$, $1$, $2$, $3$ and $4$.

**Solution of Exercise 18.13.**

Take a way of paying an amount with the fewest coins: $f$ coins of $5$, $t$ of $2$, $u$ of $1$. Then $u \le 1$, since $1 + 1$ could become $2$; $t \le 2$, since $2 + 2 + 2$ could become $5 + 1$; and not $t = 2$ with $u = 1$, since $2 + 2 + 1$ could become $5$. So $2t + u$ is one of $0$, $1$, $2$, $2 + 1 = 3$, $2 + 2 = 4$: it is less than $5$, $f$ is the number of fives that fit, and $2t + u$ is the remainder. Each remainder from $0$ to $4$ has exactly one such way, and it is greedy’s: greedy also takes every five that fits, then a $2$ while it fits, then a $1$.

**Exercise 18.14 ★★★.**

All the requests must now be kept, in as few rooms as possible. Taking the requests by start time, give each the first room free at its start, opening a new room if none is. Write `rooms_needed(requests)` and check that it equals the largest number of requests going on at the same hour.

**Solution of Exercise 18.14.**

    `def rooms_needed(requests):`

        `rooms = []`

        `for _, start, end in sorted(requests, key=lambda r: r[1]):`

            `for i, free in enumerate(rooms):`

                `if free <= start:`

                    `rooms[i] = end`

                    `break`

            `else:`

                `rooms.append(end)`

        `return len(rooms)`

`rooms[i]` is the hour at which room `i` becomes free; the `else` of a `for` runs when the loop ended without `break`. A new room is opened only when every room is busy at that start: at that hour, as many requests as rooms, plus the new one, are going on, so no plan can use fewer rooms. The tests check the equality on $200$ random sets.

**Exercise 18.15 ★★★.**

Find three requests on which “shortest first” keeps fewer bookings than possible.

**Solution of Exercise 18.15.**

P from $8$h to $12$h, S from $11$h to $13$h, Q from $12$h to $16$h. Shortest first keeps S ($2$ h), which overlaps P and Q: one booking. P and Q together make two.

## 18.7 Problem: The Coins of Brenmoor

**Problem 18.1.**

Weekend problem — the amounts greedy gets wrong

The town of Brenmoor, invented for this problem, mints coins of $1$, $2$, $5$, $12$, $25$ and $40$. Its shopkeepers give change greedily. The program compares greedy with the exhaustive search on every amount up to $100$, then tries every way of changing one coin.

```python
"""The weekend problem: is greedy change right with the coins of Brenmoor?"""
from change_exhaustive import fewest
from change_greedy import greedy_change

BRENMOOR = [1, 2, 5, 12, 25, 40]


def failures(coins, upto):
    return [a for a in range(1, upto + 1)
            if len(greedy_change(a, coins)) > fewest(a, coins)[0]]


bad = failures(BRENMOOR, 100)
a = bad[0]
print("smallest failure:", a, "greedy", greedy_change(a, BRENMOOR),
      "fewest", fewest(a, BRENMOOR)[0])
print(len(bad), "failures up to 100:", bad)
print("fewest coins tried for 100:", fewest(100, BRENMOOR)[1], "combinations")
# Part IV: change one coin (not the 1) and check below the two largest added
for i in range(1, len(BRENMOOR)):
    for new in range(2, 50):
        coins = sorted(set(BRENMOOR[:i] + [new] + BRENMOOR[i + 1:]))
        if len(coins) == len(BRENMOOR) and not failures(coins, coins[-1] + coins[-2]):
            print(f"replace {BRENMOOR[i]} by {new}: {coins} never fails")
```

***Listing 18.7.** Greedy against the fewest coins in Brenmoor, and the systems one coin away. code/grade-11/07-greedy-algorithms/listings/brenmoor.py*

```
$ python brenmoor.py
smallest failure: 36 greedy [25, 5, 5, 1] fewest 3
17 failures up to 100: [36, 49, 50, 51, 55, 60, 61, 62, 63, 74, 75, 76, 89, 90, 91, 95, 100]
fewest coins tried for 100: 3687 combinations
replace 12 by 10: [1, 2, 5, 10, 25, 40] never fails
replace 25 by 3: [1, 2, 3, 5, 12, 40] never fails
replace 25 by 19: [1, 2, 5, 12, 19, 40] never fails
replace 25 by 26: [1, 2, 5, 12, 26, 40] never fails
```

***Output 18.7.** The failures, and four ways to remove them all by changing one coin.*

**Part I — The coins.**

1. Give greedy change for $24$ , $30$ and $37$ .
2. Why must a coin system contain a coin of $1$ for greedy to pay every amount?
3. By the theorem, below which amount must a failure appear, if there is one?
4. Why does the program still check up to $100$ ?

**Part II — Greedy against the fewest.**

5. Give greedy change for $36$ , and a way with fewer coins.
6. By the theorem’s lower bound, which amounts cannot be the first failure? Which amounts did the program have to examine before finding $36$ ?
7. For $49$ and $50$ , give greedy’s change and a better one.
8. The exhaustive search tries $3687$ combinations for $100$ . Why does greedy need only a few steps?
9. Is the system [canonical](#def-g11-greedy-algorithms-canonical) ?

**Part III — The failures.**

10. What do $36$ , $61$ and $76$ have in common in their best change?
11. For $60$ , $61$ , $62$ and $63$ , give greedy’s change and a way with fewer coins.
12. How many coins too many does greedy give for $100$ ? Find a way with only four.
13. How many of the amounts $1$ to $100$ fail?

**Part IV — Changing one coin.**

14. Replacing $12$ by $10$ gives a [canonical](#def-g11-greedy-algorithms-canonical) system. Up to which amount did the program have to check, and why is that enough?
15. Check by hand that $36$ no longer fails with $1$ , $2$ , $5$ , $10$ , $25$ , $40$ .
16. Replacing $25$ by $26$ also works. Check $36$ and $50$ in that system.
17. Why does the program skip replacements that give a coin already in the system?
18. Brenmoor prefers to keep its $12$ and its $40$ . Which replacements allow it?
19. Name an advantage for the town of a [canonical](#def-g11-greedy-algorithms-canonical) system.
20. State the result: the smallest amount greedy gets wrong in Brenmoor, and how many amounts up to $100$ it gets wrong.

**Solution of Problem 18.1.**

**1.** $24 = 12 + 12$; $30 = 25 + 5$; $37 = 25 + 12$: two coins each.

**2.** Without a coin of $1$, some amounts cannot be paid at all, and greedy may leave a remainder smaller than every coin, as $3$ with coins of $2$ and $5$ after taking nothing, or $1$ after taking a $2$.

**3.** Below $c_m + c_{m-1} = 40 + 25 = 65$.

**4.** The theorem places the first failure; the question asks for all of them up to $100$.

**5.** Greedy: $25 + 5 + 5 + 1$, four coins. Better: $12 + 12 + 12$, three.

**6.** The first failure is above $c_3 + 1 = 6$: amounts $1$ to $6$ cannot be it. The program examined $7$ to $36$ (and, without knowing the theorem, $1$ to $6$ too) before finding $36$.

**7.** $49$: greedy $40 + 5 + 2 + 2$, four coins; $25 + 12 + 12$, three. $50$: greedy $40 + 5 + 5$, three; $25 + 25$, two.

**8.** One division per coin value, six in all, whatever the amount; the search tries combinations of all the coins.

**9.** No: $36$ fails.

**10.** Their best change uses three coins of $12$: $36 = 3 \times 12$, $61 = 25 + 3 \times 12$, $76 = 40 + 3 \times 12$. Greedy takes a larger coin first and can no longer use three $12$.

**11.** $60$: greedy $40 + 12 + 5 + 2 + 1$, five; $25 + 25 + 5 + 5$, four. $61$: greedy $40 + 12 + 5 + 2 + 2$, five; $25 + 12 + 12 + 12$, four. $62$: greedy $40 + 12 + 5 + 5$, four; $25 + 25 + 12$, three. $63$: greedy $40 + 12 + 5 + 5 + 1$, five; $25 + 25 + 12 + 1$, four.

**12.** Greedy gives $40 + 40 + 12 + 5 + 2 + 1$, six coins; $25 + 25 + 25 + 25$ needs four: two too many. $100$ is the only amount up to $100$ where greedy loses two coins.

**13.** $17$.

**14.** Up to $40 + 25 = 65$; by the theorem, a system that does not fail below that never fails.

**15.** Greedy gives $25 + 10 + 1$, three coins; two coins cannot make $36$ ($40$ is too large, and no two of $25$, $10$, $5$, $2$, $1$ add to $36$).

**16.** $36$: greedy $26 + 5 + 5$, three, as many as $12 \times 3$. $50$: greedy $40 + 5 + 5$, three; with $25$ gone, no two coins make $50$.

**17.** A coin already present would leave five different coins: the system is not one coin changed, but one coin removed.

**18.** Replacing $25$ by $3$, by $19$ or by $26$.

**19.** Shopkeepers can follow the quickest rule and still give the fewest coins, so fewer coins change hands and fewer need to be minted.

**20.** In Brenmoor greedy change **first goes wrong at $36$**, giving four coins where three of $12$ suffice, and it goes wrong on **$17$ amounts up to $100$**.
