Memra

When greedy works vs when it fails: knapsack

◈ 5 cards

Fractional knapsack is solvable greedily by value density; 0/1 knapsack is not — the W=50 counterexample shows why 0/1 needs DP.

The same problem, two versions

A thief finds items; item has value and weight , and the knapsack holds weight . The two versions diverge on a single rule:

  • Fractional knapsack — you may take any fraction of an item (think gold dust). Greedy works.
  • 0/1 knapsack — each item is taken whole or left behind (think gold bars). Greedy fails; you need DP.

Fractional knapsack: greedy by value density

Compute each item's value density , sort descending, and greedily fill the knapsack with the highest-density items, taking a fraction of the last one if it does not fit. This is (the sort dominates).

Why it is safe (exchange argument): if an optimal solution skipped some of a higher-density item to include a lower-density one, you could swap a sliver of the low-density portion for the high-density portion, raising the value without changing the weight — contradicting optimality. Because fractions are allowed, the greedy choice never wastes capacity.

0/1 knapsack: the greedy counterexample

Take and three items (CLRS Fig. 15.2):

Greedy (by density) takes item 1 ($\$60$, density 6), then item 2 ($\$100$, density 5) for weight $30$ and value $\$160$; item 3 no longer fits. Optimal skips the densest item: items 2 + 3 weigh exactly 50 and are worth $\$220$. Greedy left 20 pounds of capacity "wasted" on the lower-value item 1.

The fractional version of the same instance reaches $\$240$: take all of items 1 and 2 ($30\$160\tfrac{20}{30}$ of item 3 ($\$80$). Allowing fractions removes the wasted-capacity trap.

Why 0/1 needs DP

In the 0/1 problem, choosing one item reduces the capacity available to all others — the subproblems share the weight constraint, so the greedy choice can foreclose a better combination. That shared constraint is exactly the overlapping-subproblem structure DP exploits. The DP is

in time. (That is pseudo-polynomial — polynomial in the numeric value of , but exponential in the number of bits used to write . 0/1 knapsack is NP-complete.)

greedyi1i1i2i2i2i2$160 packed20 lb strandedoptimali2i2i2i2i3i3i3i3i3i3$220, fullfractionali1i1i2i2i2i2i3i3i3i3$240, full (2/3 of i3)i1 = $60/10 lb (density 6), i2 = $100/20 lb (density 5), i3 = $120/30 lb (density 4). Taking the densestitem whole is what strands the capacity.
W = 50 as ten 5-lb slots. Greedy grabs the densest item first and cannot fill the last 20 lb; the optimum skips it.
fractional0/1take part of an item?yesnogreedy by densityoptimal ($240)wrong ($160)capacity left unusednone20 lbalgorithm neededsort, O(n lg n)DP, O(nW)Greedy correctness is a property of the problem, not of the heuristic — prove the greedy-choice propertybefore trusting it.
One rule change — divisibility — flips greedy from optimal to wrong.
NORMAL ~/memra/learn/comp-372/fractional-vs-01-knapsack utf-8 LF