Sub topic 4
A Counterexample: Greedy Fails for 0/1 Knapsack
This chapter assumes you can read Python functions and loops, follow a short proof by contradiction, and use Big-O notation. It builds on the previous chapter, where sorting by value per unit of weight solved the fractional knapsack problem optimally.
The obvious next step is to reuse that greedy rule for the 0/1 problem, where each item is taken whole or left behind. The rule looks reasonable, and on many inputs it gives the right answer. On some inputs it does not, and this chapter shows exactly why.
The Greedy Rule Applied to 0/1 Items
The 0/1 version of the greedy algorithm sorts items by ratio value / weight, highest first. It then walks the list and takes every item that still fits whole. Unlike the fractional version, it cannot take part of an item, so an item that does not fit is skipped and the scan moves on.
Take the running example from the fractional chapter: capacity 50 and three items.
| Item | Value | Weight | Ratio |
|---|---|---|---|
| 0 | 60 | 10 | 6.0 |
| 1 | 100 | 20 | 5.0 |
| 2 | 120 | 30 | 4.0 |
Greedy takes item 0 (10 units of capacity used, 40 left), then item 1 (20 more, 20 left). Item 2 weighs 30 and no longer fits. The result is value 160.
Now look at items 1 and 2 together. Their weights sum to exactly 50 and their values sum to 220. The best-ratio item, which greedy picked first, is not part of the optimal answer.
The 20 units of capacity that greedy leaves empty are what it loses. In the fractional problem greedy would fill them with two-thirds of item 2 and reach 240. In the 0/1 problem that space has to go to waste.
Why the Fractional Proof Breaks
The fractional proof is an exchange argument. Suppose some optimal solution holds less of the best-ratio item than greedy does. You can then remove a sliver of a worse item and replace it with the same weight of the better item, and the value does not go down. Repeat this and you reach the greedy solution without ever losing value.
That argument needs slivers. In the 0/1 problem the only possible exchanges swap whole items, and whole items rarely have equal weights. Swapping item 2 (weight 30) for item 0 (weight 10) in the optimal solution frees 20 units, but no unused item fits there except item 0 itself. Each exchange step changes how much capacity is used, so a higher ratio no longer guarantees higher total value.
The underlying problem is that the 0/1 problem lacks the greedy-choice property. Even the locally best item can belong to no optimal solution.
Every Simple Greedy Rule Has a Counterexample
You might hope a different sort key fixes the problem. It does not. The code below runs three greedy rules and compares them against exhaustive search.
from itertools import combinations
def greedy_01(items, capacity, key):
# items: list of (value, weight); take whole items in key order while they fit
total = 0
chosen = []
for i in sorted(range(len(items)), key=lambda i: key(items[i]), reverse=True):
value, weight = items[i]
if weight <= capacity:
chosen.append(i)
total += value
capacity -= weight
return total, sorted(chosen)
def brute_force(items, capacity):
best = (0, [])
for r in range(len(items) + 1):
for combo in combinations(range(len(items)), r):
weight = sum(items[i][1] for i in combo)
if weight <= capacity:
value = sum(items[i][0] for i in combo)
if value > best[0]:
best = (value, list(combo))
return best
rules = {
"ratio": lambda it: it[0] / it[1],
"value": lambda it: it[0],
"lightest": lambda it: -it[1],
}
instances = [
([(60, 10), (100, 20), (120, 30)], 50),
([(10, 10), (9, 5), (9, 5)], 10),
]
for items, capacity in instances:
print("capacity", capacity, "items", items)
print(" optimal ", brute_force(items, capacity))
for name, key in rules.items():
print(" %-8s" % name, greedy_01(items, capacity, key))Output:
capacity 50 items [(60, 10), (100, 20), (120, 30)]
optimal (220, [1, 2])
ratio (160, [0, 1])
value (220, [1, 2])
lightest (160, [0, 1])
capacity 10 items [(10, 10), (9, 5), (9, 5)]
optimal (18, [1, 2])
ratio (18, [1, 2])
value (10, [0])
lightest (18, [1, 2])Each rule fails on some instance:
| Rule | Fails on | Greedy | Optimal | What goes wrong |
|---|---|---|---|---|
| Highest ratio | Instance 1 | 160 | 220 | Leaves capacity that nothing remaining fits into |
| Highest value | Instance 2 | 10 | 18 | One big item crowds out two good ones |
| Lightest first | Instance 1 | 160 | 220 | Packs many small, cheap items |
Any rule that commits to items one at a time, without looking at how the remaining capacity will be filled, runs into this kind of failure.
How Bad Can Ratio Greedy Get?
The gap is not limited to a constant amount. Take capacity W and two items:
- Item A: value 2, weight 1 (ratio 2)
- Item B: value
W, weightW(ratio 1)
Greedy takes A first. The remaining capacity is W - 1, so B no longer fits. Greedy ends with value 2 while the optimum is W. With W = 1000 greedy gets 0.2% of the optimum, and the ratio between optimum and greedy grows without limit as W grows.
items = [(2, 1), (1000, 1000)]
print(greedy_01(items, 1000, rules["ratio"])) # (2, [0])
print(brute_force(items, 1000)) # (1000, [1])Searching for Counterexamples Yourself
Finding failures by hand teaches less than watching a program find them. The script below generates random small instances and stops at the first one where ratio greedy loses.
import random
random.seed(1)
for trial in range(10000):
n = random.randint(2, 5)
items = [(random.randint(1, 20), random.randint(1, 10)) for _ in range(n)]
capacity = random.randint(5, 20)
g = greedy_01(items, capacity, rules["ratio"])
b = brute_force(items, capacity)
if g[0] < b[0]:
print("trial", trial, "capacity", capacity, "items", items)
print(" greedy", g, "optimal", b)
breakA failure turns up within a few trials. Read the printed instance and find the unused capacity in the greedy solution. Almost every failure has the same shape: an early high-ratio item uses up just enough room to block a heavier, more valuable item.
Common Mistakes
- Stopping at the first item that does not fit. Some implementations
breakwhen an item fails to fit. That throws away smaller items later in the list that would still fit. The version above keeps scanning, but it is still wrong in general. - Testing only on friendly inputs. Greedy is right on many instances, including any where all weights are equal. A few passing tests prove nothing, so compare against brute force on random small cases.
- Assuming the fractional answer is achievable. The value 240 is a bound, not a packing. Rounding a fractional solution down to whole items gives the greedy result, not the optimum.
What This Means for the Rest of the Tutorial
No single item can be committed to safely. The correct algorithm therefore has to keep both choices open for every item, take it or leave it, and compare the results. Done naively, that is the exhaustive search from earlier. The next chapter shows that the two choices lead to smaller subproblems of the same form, which turns the search into a recurrence that dynamic programming can solve efficiently.
Exercise
With capacity 10, find an instance with exactly two items where greedy by ratio (taking whole items while they fit) returns less than half of the optimal value. Give the greedy value and the optimal value.
Show answer
One answer is item A = (value 2, weight 1) and item B = (value 10, weight 10). A has ratio 2 and B has ratio 1, so greedy takes A, leaving capacity 9, and B does not fit. Greedy gets 2 and the optimum is 10, which is 20% of optimal. Any instance where a light high-ratio item blocks a single item that fills the whole capacity works.
Exercise
Why does ratio greedy always give the optimal 0/1 answer when every item has the same weight?
Show answer
With equal weights w, the knapsack holds exactly floor(capacity / w) items whatever you choose, so the problem reduces to picking that many items with the largest total value. Ratio order equals value order when weights are equal, so greedy picks the most valuable items. No capacity can be wasted in a way that a different choice would avoid.
Exercise
On the instance capacity 50, items (60,10), (100,20), (120,30), compute the patched greedy from the tip: the maximum of the ratio-greedy value and the best single item. Is it optimal here, and does it meet the half-of-optimal guarantee?
Show answer
Ratio greedy gives 160. The best single item is 120. The maximum is 160, which is not optimal (220) but is above 110, half of 220, so the guarantee holds.