本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
18Greedy Algorithms
A shopkeeper owes in change and has coins of , , , , and . Without thinking she hands over the largest coin that fits, , then again the largest that fits what is left, , then , , : 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). The cost of an algorithm counts its elementary operations (chapter 17); an invariant is kept by each turn of a loop (chapter 16).
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 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.
"""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}")
$ python change_exhaustive.py
20 with 1, 2, 5: (4, 29)
amounts below 70 where greedy is not optimal: []
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)
- Choose the rule: the order in which candidates are looked at, often a sort by a well-chosen key.
- Take each candidate that keeps the solution feasible.
- Prove that the result is optimal, often by exchange: take any optimal solution, and change it, step by step, into the greedy one without making it worse.
- If there is no proof, look for a counter-example with a program that compares greedy with an exhaustive search on small inputs.
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")
$ 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
With the coins , , an exchange argument proves greedy right. Take a way of paying with the fewest coins. It uses at most one coin of , since two could become one ; at most two coins of , since three could become a and a ; and never two with a , which could become a . So the coins of and add up to at most , and every that fits is used, exactly as greedy does; what remains, to , has only one way with these rules: , , , , , again greedy’s way. Greedy and an optimal solution 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 , with . If greedy change gives more coins than necessary for some amount, then it does so already for some amount with .
Proof. Admitted at this level. ∎
For , , , , , , it is enough to check every amount below , 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.
"""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)))
$ 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
Why is it optimal? Let be the bookings greedy keeps, in order, and those of an optimal choice, in order. Greedy “stays ahead”: ends no later than , since greedy took the request that ends first. If ends no later than , then , which starts after ends, starts after ends too; so it was still available to greedy, which took a request ending no later, and ends no later than . Greedy can therefore never run out before the optimal choice does: it keeps at least as many bookings.
18.4 Filling a knapsack
A trader’s sack holds 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.
"""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)
$ python knapsack_fractional.py
spices 2 kg
tea 4 kg
coffee 6 kg
rice 3 kg
value: 194.0
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.
"""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])
$ python knapsack_01_greedy_fails.py
greedy keeps ['A'] value 30
every subset tried: best ['B', 'C'] value 40
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 , and , greedy pays as , three coins, while needs two. The program below looks, among all systems of three coins up to , for those that are not canonical, and for the first amount each gets wrong; the theorem says to look only below the sum of the two largest coins.
"""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]}")
$ 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
18.6 Exercises
Exercise 18.1 ★
Give greedy change for with coins , , , , , , without the program.
Solution
Solution of Exercise 18.1.
leaves ; leaves ; leaves ; leaves ; leaves : five coins, .
Exercise 18.2 ★
With coins , , , how many coins does greedy give for ? How many are needed?
Solution
Solution of Exercise 18.2.
Greedy gives , three coins; needs two.
Exercise 18.3 ★
Four requests: P from h to h, S from h to h, Q from h to h, R from h to h. Which does earliest end first keep?
Solution
Solution of Exercise 18.3.
By end hour: P (h), S (h), R (h), Q (h). P is kept; S starts at h, before h: no; R starts at h: kept; Q starts at h, before h: no. P and R, two bookings, as many as possible.
Exercise 18.4 ★
With the goods of the chapter and a sack of kg, what does the fractional greedy take, and for what value?
Solution
Solution of Exercise 18.4.
Spices ( kg, ), tea ( kg, ), then of the kg of coffee, worth : in all .
Exercise 18.5 ★
Write greedy_change(amount, coins) with divmod, one division per coin value.
Solution
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
Solution of Exercise 18.6.
L from h to h, x from h to h, y from h to h, z from h to 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
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 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 , then of .
Solution
Solution of Exercise 18.8.
With coins of , from to , the rest is paid with and , trying every number of coins of : , , , and ways for to . In all , as printed.
Exercise 18.9 ★★
With a sack of 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
Solution of Exercise 18.9.
By value per kilogram: spices, tea, and kg of coffee, . By value: coffee (, kg) and tea (, kg), . 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 kg worth , Y and Z of kg worth each; the sack holds kg. What does greedy by value per kilogram keep, and what is optimal?
Solution
Solution of Exercise 18.10.
Values per kilogram: X , Y and Z . Greedy keeps X ( kg), and then neither Y nor Z fits: value . Y and Z together weigh kg and are worth , which is optimal.
Exercise 18.11 ★★
Write is_canonical_upto(coins, m) that compares greedy with fewest on every amount from to . With the theorem, which makes it a full test?
Solution
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, , 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
Solution of Exercise 18.12.
Let the requests be sorted by end hour, and let be an optimal choice, in order of time. Invariant of the loop: after greedy has kept , with , each ends no later than . It holds for . When greedy has and , the request starts after ends, hence after ends: it is compatible with what greedy kept, and greedy, scanning by end hour, keeps a request no later than in that order, so its ends no later than . The invariant is kept as long as , so greedy keeps at least requests, and therefore exactly , 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 , , by treating the amounts left after the coins of : , , , and .
Solution
Solution of Exercise 18.13.
Take a way of paying an amount with the fewest coins: coins of , of , of . Then , since could become ; , since could become ; and not with , since could become . So is one of , , , , : it is less than , is the number of fives that fit, and is the remainder. Each remainder from to has exactly one such way, and it is greedy’s: greedy also takes every five that fits, then a while it fits, then a .
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
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 random sets.
Exercise 18.15 ★★★
Find three requests on which “shortest first” keeps fewer bookings than possible.
Solution
Solution of Exercise 18.15.
P from h to h, S from h to h, Q from h to h. Shortest first keeps S ( 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 , , , , and . Its shopkeepers give change greedily. The program compares greedy with the exhaustive search on every amount up to , then tries every way of changing one coin.
"""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")
$ 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
Part I — The coins.
- Give greedy change for , and .
- Why must a coin system contain a coin of for greedy to pay every amount?
- By the theorem, below which amount must a failure appear, if there is one?
- Why does the program still check up to ?
Part II — Greedy against the fewest.
- Give greedy change for , and a way with fewer coins.
- By the theorem’s lower bound, which amounts cannot be the first failure? Which amounts did the program have to examine before finding ?
- For and , give greedy’s change and a better one.
- The exhaustive search tries combinations for . Why does greedy need only a few steps?
- Is the system canonical?
Part III — The failures.
- What do , and have in common in their best change?
- For , , and , give greedy’s change and a way with fewer coins.
- How many coins too many does greedy give for ? Find a way with only four.
- How many of the amounts to fail?
Part IV — Changing one coin.
- Replacing by gives a canonical system. Up to which amount did the program have to check, and why is that enough?
- Check by hand that no longer fails with , , , , , .
- Replacing by also works. Check and in that system.
- Why does the program skip replacements that give a coin already in the system?
- Brenmoor prefers to keep its and its . Which replacements allow it?
- Name an advantage for the town of a canonical system.
- State the result: the smallest amount greedy gets wrong in Brenmoor, and how many amounts up to it gets wrong.
Solution
Solution of Problem 18.1.
1. ; ; : two coins each.
2. Without a coin of , some amounts cannot be paid at all, and greedy may leave a remainder smaller than every coin, as with coins of and after taking nothing, or after taking a .
3. Below .
4. The theorem places the first failure; the question asks for all of them up to .
5. Greedy: , four coins. Better: , three.
6. The first failure is above : amounts to cannot be it. The program examined to (and, without knowing the theorem, to too) before finding .
7. : greedy , four coins; , three. : greedy , three; , two.
8. One division per coin value, six in all, whatever the amount; the search tries combinations of all the coins.
9. No: fails.
10. Their best change uses three coins of : , , . Greedy takes a larger coin first and can no longer use three .
11. : greedy , five; , four. : greedy , five; , four. : greedy , four; , three. : greedy , five; , four.
12. Greedy gives , six coins; needs four: two too many. is the only amount up to where greedy loses two coins.
13. .
14. Up to ; by the theorem, a system that does not fail below that never fails.
15. Greedy gives , three coins; two coins cannot make ( is too large, and no two of , , , , add to ).
16. : greedy , three, as many as . : greedy , three; with gone, no two coins make .
17. A coin already present would leave five different coins: the system is not one coin changed, but one coin removed.
18. Replacing by , by or by .
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 , giving four coins where three of suffice, and it goes wrong on amounts up to .