Sub topic 4
When Greedy Fails: Coin Change and Other Counterexamples
This chapter assumes you can read Python functions and loops, know Big-O notation, and have met the greedy choice property and optimal substructure in the previous chapters. It does not assume any proof techniques yet. Those come next.
A greedy algorithm makes the best-looking choice at each step and never revisits it. This is fast, and it is often wrong. Before you invest effort in proving a greedy rule correct, try to break it. A single input where the greedy answer is worse than the best possible answer is a counterexample, and it settles the question for good. This chapter shows the classic counterexamples, the ways greedy rules typically fail, and a mechanical method for hunting counterexamples with code.
Coin Change: The Standard Warning
The problem: given coin denominations and a target amount, use the fewest coins that sum exactly to the amount. The obvious greedy rule is to take the largest coin that still fits, and repeat.
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 for every amount. With {1, 3, 4} it fails at 6. Taking the 4 looks best locally, but it leaves a remainder of 2 that only 1-coins can cover. The optimal solution [3, 3] does not contain the greedy first choice at all. That is exactly a violation of the greedy choice property: no optimal solution starts with the choice greedy made.
Greedy can fail to find any answer
When there is no 1-coin, the failure can be worse than suboptimal:
print(greedy_coins([3, 5], 9)) # None, yet 3 + 3 + 3 = 9Greedy takes 5, leaves 4, takes 3, leaves 1, and gets stuck. A valid answer exists, but greedy commits early and never backs up, so it reports none. Keep this in mind: a greedy rule can break feasibility as well as optimality.
Testing a coin system mechanically
You can compare greedy with an exact solver over a range of amounts. The exact solver below uses a small table where best[a] is the fewest coins summing to a. That is dynamic programming, which a later chapter covers. Here it serves only as a reference answer.
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 optimal_count(coins, amount):
INF = float("inf")
best = [0] + [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 first_counterexample(coins, limit):
for amount in range(1, limit + 1):
g = greedy_coins(coins, amount)
g_count = len(g) if g is not None else float("inf")
opt = optimal_count(coins, amount)
if g_count != opt:
return amount, g, opt
return None
print(first_counterexample([1, 5, 10, 25], 200)) # None
print(first_counterexample([1, 3, 4], 200)) # (6, [4, 1, 1], 2)
print(first_counterexample([1, 7, 10], 200)) # (14, [10, 1, 1, 1, 1], 2)
print(first_counterexample([3, 5], 200)) # (6, None, 2)How far do you need to search? Kozen and Zaks (1994) showed that if a coin system has a counterexample, the smallest one is less than the sum of the two largest coins. For [1, 5, 10, 25] that bound is 35, so testing up to 200 is more than enough to certify the system.
Interval Scheduling: Plausible Rules That Lose
The problem: given intervals (start, end), choose as many as possible so that no two overlap. A later chapter proves that "earliest finish time first" is optimal. Several other rules sound just as sensible and fail.
| Greedy rule | Counterexample | Greedy picks | Optimum |
|---|---|---|---|
| Earliest start | (0, 10), (1, 2), (3, 4) | 1: (0, 10) | 2: (1, 2), (3, 4) |
| Shortest interval | (0, 5), (4, 7), (6, 11) | 1: (4, 7) | 2: (0, 5), (6, 11) |
| Fewest conflicts | Known 11-interval layout | 3 | 4 |
| Earliest finish | None exists | optimal | optimal |
Each failing rule optimizes a stand-in for the real goal. Starting early, being short, and having few conflicts all correlate with leaving room for later intervals, but none of them guarantees it. Finishing earliest does guarantee it, because it leaves the largest possible remainder of the timeline.
The fewest-conflicts rule survives every small hand-built example people usually try. Its counterexample needs about a dozen intervals. This is why you should search by code instead of trusting a few hand examples.
Randomized counterexample search
The method: generate many small random inputs, solve each one by brute force, and compare with the greedy answer. Small inputs keep the brute force cheap, and most bugs in greedy rules show up on small inputs.
import random
from itertools import combinations
def compatible(ivs):
ivs = sorted(ivs)
return all(a[1] <= b[0] for a, b in zip(ivs, ivs[1:]))
def best_size(ivs):
for k in range(len(ivs), 0, -1):
if any(compatible(c) for c in combinations(ivs, k)):
return k
return 0
def greedy_by(ivs, key):
chosen = []
for iv in sorted(ivs, key=key):
if all(iv[1] <= c[0] or c[1] <= iv[0] for c in chosen):
chosen.append(iv)
return chosen
rules = {
"earliest start": lambda iv: iv[0],
"shortest": lambda iv: iv[1] - iv[0],
"earliest finish": lambda iv: iv[1],
}
random.seed(1)
for name, key in rules.items():
found = None
for _ in range(2000):
ivs = []
for _ in range(5):
s = random.randint(0, 10)
ivs.append((s, s + random.randint(1, 5)))
if len(greedy_by(ivs, key)) < best_size(ivs):
found = ivs
break
print(f"{name:16} counterexample: {found}")The first two rules print a small failing input. "Earliest finish" prints None. A None here is evidence, not proof. Random testing can only show that a rule is wrong, and you still need an argument to show it is right.
0/1 Knapsack: Ratio Greedy Breaks
In the fractional knapsack, where you may take part of an item, taking items by value per weight is optimal. Forbid splitting and the same rule fails:
from itertools import combinations
def greedy_01(items, cap):
total = 0
for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
if weight <= cap:
total += value
cap -= weight
return total
def brute_01(items, cap):
best = 0
for k in range(len(items) + 1):
for combo in combinations(items, k):
if sum(w for _, w in combo) <= cap:
best = max(best, sum(v for v, _ in combo))
return best
items = [(60, 10), (100, 20), (120, 30)]
print(greedy_01(items, 50)) # 160
print(brute_01(items, 50)) # 220Greedy takes the items with ratio 6 and ratio 5, using 30 units. The remaining 20 units cannot hold the 30-unit item, so that capacity is wasted. The optimum skips the best-ratio item entirely. Greedy fails here because of indivisibility. Once items cannot be split, a locally good item can block a better combination.
Common Failure Patterns
Most broken greedy rules fail in one of a few recognizable ways:
- Lumpy choices. Coins and 0/1 items come in fixed sizes. Taking the biggest piece can leave a remainder that fits badly. Fractional versions usually lack this problem.
- Proxy objectives. The rule optimizes something correlated with the goal (short, early, few conflicts) rather than the quantity that actually governs future options.
- Blocking. An early choice removes options later, as in the
{3, 5}coin case where greedy never reaches a feasible state. - Hidden later costs. In shortest paths with negative edges, a path that looks long now can become cheaper later. Greedy has already finalized its answer by then. The Dijkstra chapter returns to this.
- Myopic tours. For the traveling salesperson problem, "go to the nearest unvisited city" can be forced into a very long final edge back to the start.
What a Counterexample Tells You
A counterexample shows that one specific rule is not optimal. It does not show that no greedy rule works. Interval scheduling has three failing rules and one correct one. When your rule fails, you can respond in three ways:
- Look for a different greedy criterion that fixes the failure you observed.
- Use dynamic programming when the problem has optimal substructure but no safe greedy choice, as with general coin change and 0/1 knapsack.
- Accept the greedy answer as an approximation with a provable bound, when exact solutions are too expensive.
Exercise
Find the smallest amount where greedy fails for the coin system {1, 4, 5}, and give both the greedy and the optimal coin lists.
Show answer
The smallest such amount is 8. Greedy takes 5, then 1, 1, 1, which is four coins. The optimal answer is 4 + 4, which is two coins. Amounts 1 through 7 are all handled optimally by greedy, and 8 is below the Kozen–Zaks bound of 4 + 5 = 9.
Exercise
Someone proposes scheduling intervals by "latest start time first," adding each interval that does not overlap those already chosen. Is this rule optimal? Justify your answer.
Show answer
Yes. It is the mirror image of earliest finish first. Reverse the timeline by mapping each interval (s, e) to (-e, -s). Latest start becomes earliest finish, and overlap is unchanged, so the rule inherits the optimality of earliest finish first. Running the randomized tester with key=lambda iv: -iv[0] finds no counterexample, which agrees with this argument.
Exercise
For 0/1 knapsack, a different greedy rule takes items by highest value first. Give a counterexample with capacity 10.
Show answer
Use the items (value 10, weight 10), (value 9, weight 5), and (value 9, weight 5). Highest value first takes the 10-value item and fills the knapsack, for a total of 10. Taking the two 9-value items fits exactly and gives 18.