Sub topic 4
When Greedy Fails: Coin Change and Other Counterexamples
This chapter assumes you can read Python functions and loops, and that you know the greedy choice property and optimal substructure from the previous chapters. Here you will see what happens when the greedy choice property does not hold. You will also learn a quick way to find a counterexample before you spend time on a proof.
Coin change: the classic trap
Coin change asks for the fewest coins that add up to an amount. The obvious greedy rule is to take the largest coin that still fits, and keep doing that until the amount reaches zero.
def greedy_coins(coins, amount):
used = []
for c in sorted(coins, reverse=True):
while amount >= c:
amount -= c
used.append(c)
return used if amount == 0 else None
print(greedy_coins([1, 5, 10, 25], 63)) # [25, 25, 10, 1, 1, 1]
print(greedy_coins([1, 3, 4], 6)) # [4, 1, 1], but [3, 3] uses only 2 coinsWith US denominations, the rule is optimal. With {1, 3, 4}, taking the 4 first leaves 2, and the only way to pay 2 is with two 1s. Taking the largest coin was locally best, but it ruled out the better solution 3 + 3. A greedy algorithm never goes back on a choice, so it cannot recover from that one.
Greedy can also fail to find any answer. With coins {3, 5} and amount 9, greedy takes 5, then 3, and is left with 1, which no coin can pay. Meanwhile 3 + 3 + 3 works.
Finding counterexamples by brute force
You don't have to guess small cases by hand. Compare the greedy result with an exact dynamic-programming answer over a range of amounts:
def min_coins(coins, amount):
best = [0] + [float("inf")] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
return best[amount]
def greedy_coins(coins, amount):
used = []
for c in sorted(coins, reverse=True):
while amount >= c:
amount -= c
used.append(c)
return used if amount == 0 else None
def first_failure(coins, limit=100):
for amount in range(1, limit + 1):
g = greedy_coins(coins, amount)
g_count = len(g) if g is not None else float("inf")
if g_count != min_coins(coins, amount):
return amount
return None
print(first_failure([1, 5, 10, 25])) # None
print(first_failure([1, 3, 4])) # 6Other common failures
The same pattern shows up in other problems. In each case, a sort order that looks reasonable turns out to be the wrong one.
| Problem | Tempting greedy rule | Counterexample | Greedy result | Optimal |
|---|---|---|---|---|
| Interval scheduling | Shortest interval first | (0,5), (4,6), (5,10) | 1 interval | 2 intervals |
| Interval scheduling | Earliest start first | (0,10), (1,2), (3,4) | 1 interval | 2 intervals |
| 0/1 knapsack, capacity 50 | Best value per weight | (60,10), (100,20), (120,30) | 160 | 220 |
In the knapsack row, greedy takes the items worth 60 and 100, which use 30 of the 50 units of capacity. The item worth 120 weighs 30, so it no longer fits, and 20 units go unused. When items cannot be split, a locally best choice can waste capacity that a different combination would have filled.
Common errors
- Assuming that because greedy is optimal for one set of inputs, it is optimal for every input to the same problem.
- Trying only "nice" test cases, such as evenly spaced coins or intervals of equal length.
- Not handling the case where greedy finds no solution at all (the
Noneabove).
Exercise
With coins {1, 7, 10}, what does greedy return for amount 14, and what is the optimal answer?
Show answer
Greedy takes 10 and then four 1s, which is 5 coins. The optimal answer is 7 + 7, which is 2 coins.
Exercise
Give a set of intervals where "fewest overlaps with other intervals first" fails for activity selection, or explain how you would search for one.
Show answer
Run a brute-force search: generate small random interval sets, compute the true maximum by trying every subset, and compare it with the rule's result. Hand-built examples exist too, such as rows of intervals where the interval with the fewest conflicts sits in the middle and blocks two members of the optimal set. The general method is to check the rule against an exact solver instead of trusting intuition.