Discrete Mathematics and Combinatorics
The Knapsack Problem and the Limits of Greedy Thinking
Learn why grabbing the best value per kilogram can fail, and how a small table finds the best way to fill a limited bag.
Key takeaways
- In the 0/1 knapsack problem each item is either taken whole or left behind, and the total weight must not exceed the capacity.
- Choosing by best value-to-weight ratio is optimal when items can be cut into fractions but can fail badly when they cannot.
- Dynamic programming solves the problem exactly by filling a table indexed by items and capacity.
- The table method is fast for small whole-number capacities but is not a polynomial-time algorithm in the technical sense.
- Efficient methods can guarantee answers within any chosen percentage of the best.
The knapsack problem asks which items to pack when each has a weight and a value and your bag can carry only so much. You want the greatest total value that fits. The tempting strategy, taking items with the best value per unit of weight first, can give a clearly worse answer than the best one.
It looks like a packing puzzle, but it is really a model for any choice under a single budget: which projects to fund, which files to save, which cargo to load. Studying it shows where simple instincts work, where they fail and what to do instead.
Where greed goes wrong
Your bag holds 10 kilograms. You have three items:
| Item | Weight | Value | Value per kg |
|---|---|---|---|
| A | 6 | 30 | 5 |
| B | 5 | 20 | 4 |
| C | 5 | 20 | 4 |
Going by ratio, you take A first. That leaves 4 kilograms, and neither B nor C fits. Total value: 30.
The better choice skips A and takes B and C, which weigh exactly 10 and are worth 40. The item with the best ratio left space you could not use. Taking the most valuable item first fails here for the same reason.
You can make the gap far worse. With capacity 100, give one item weight 1 and value 2, and another weight 100 and value 100. Ratio order takes the small item, after which the big one no longer fits. You get 2 instead of 100.
When greed is exactly right
Suppose the items are bags of rice or other divisible goods, and you may take any fraction. Then fill by ratio, and split the last item to fill the remaining space. In the first example you take all of A (30) and four fifths of B (16), for 46.
Why is this optimal? Imagine any packing that carries less of a high-ratio item than it could while carrying some of a lower-ratio one. Swap a little weight from the lower to the higher. The total weight stays the same and the value does not drop. Repeating such swaps turns any packing into the greedy one. This style of reasoning is called an exchange argument, and it is examined further in when greedy algorithms give the best answer.
The fractional answer, 46, is also useful for the whole-item version: no packing of whole items can beat it.
Solving it exactly with a table
Trying every subset works for a handful of items, but n items have 2ⁿ subsets. For 40 items that is about 1.1 trillion.
Dynamic programming avoids repeating work. Let best(k, c) be the highest value using only the first k items with capacity c. For item k with weight w and value v:
best(k, c) = best(k − 1, c) if w > c
best(k, c) = max( best(k − 1, c), leave item k
v + best(k − 1, c − w) ) take item k
best(0, c) = 0 no items, no value Take capacity 7 and items P (weight 3, value 4), Q (weight 4, value 5) and R (weight 2, value 3).
| Capacity | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| No items | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| With P | 0 | 0 | 0 | 4 | 4 | 4 | 4 | 4 |
| With P, Q | 0 | 0 | 0 | 4 | 5 | 5 | 5 | 9 |
| With P, Q, R | 0 | 0 | 3 | 4 | 5 | 7 | 8 | 9 |
The answer is 9. To find which items, trace back from the bottom right. The value at capacity 7 did not change when R was added, so R can be left out. It did change when Q was added, so Q is in, leaving capacity 3, which P fills. The packing is P and Q, weight 7.
The same example, three ways
Run the other methods on P, Q and R to see how they compare. The ratios are R at 1.5, P at about 1.33 and Q at 1.25.
| Method | What it takes | Value |
|---|---|---|
| Greedy by ratio, whole items | R, then P; Q no longer fits | 7 |
| Fractions allowed | R, P and half of Q | 9.5 |
| Exact table | P and Q | 9 |
Whole values here mean no whole-item packing can be worth more than 9 once you know the fractional bound of 9.5. So the moment you find a packing worth 9, you may stop.
Saving memory
You do not need to keep the whole table if you only want the best value. Keep a single row, one number per capacity. For each new item, update the entries from the largest capacity down to the item's weight:
- Set the entry at capacity c to the larger of its old value and v plus the entry at c − w.
- Move to c − 1 and repeat.
Going downward matters. The entry at c − w has not yet been updated, so it cannot already include the current item. If you go upward instead, an item can be used again and again, which happens to solve the version with unlimited copies. The price of the single row is that tracing back the chosen items needs extra bookkeeping.
Why this is not the end of the story
The table has about n × W entries, where W is the capacity in whole units. That looks efficient. The catch is how input size is measured. Writing the number W takes only about as many digits as its length, so a capacity with 30 digits is a short input but an impossibly large table.
An algorithm whose running time is polynomial in the numbers themselves, but not in their number of digits, is called pseudo-polynomial. The yes-or-no version of knapsack ("can we reach value V within weight W?") is NP-complete. A truly polynomial algorithm would imply that P equals NP, which most researchers doubt. For the meaning of those classes, see polynomial and exponential time.
A close relative, subset sum, asks whether some of a list of numbers add up exactly to a target. It is knapsack with each value equal to its weight.
Getting close with guarantees
A tiny fix rescues greed. Fill by ratio until the first item that does not fit. Then compare the value collected with the value of that rejected item alone (assuming every item fits by itself), and keep the better.
Together the two are worth at least the fractional optimum, which is at least the true optimum. So the better of the two is at least half the best possible.
One can do far better. Round the values to coarser units, then run a table indexed by value. Coarser rounding means a smaller table and a larger error. For any tolerance you choose, say 1 percent, this gives a guaranteed near-best answer in time polynomial in the number of items and in the reciprocal of the tolerance. Such a family of methods is called a fully polynomial-time approximation scheme. Many hard problems, including the traveling salesperson problem in its general form, allow nothing of the kind.
Searching cleverly
Exact solvers often use branch and bound. Decide items one at a time, forming a tree of choices. At each node, compute the fractional answer for what remains. If that optimistic figure cannot beat the best packing found so far, abandon the branch.
In the first example, once you have found B and C worth 40, any branch whose fractional bound is 40 or less can be dropped. On many practical instances this prunes almost everything.
The problem is also a basic case of integer programming: maximize a sum of values subject to one weight limit, with each variable 0 or 1.
Variations
- Unbounded knapsack: unlimited copies of each item.
- Bounded knapsack: a fixed stock of each item.
- Multiple constraints: limits on weight and volume at once.
- Multiple knapsacks: several bags to fill.
Hardness grows with added constraints. In particular, the strong approximation guarantee above does not carry over to two or more independent limits unless P equals NP.
Knapsack-type problems were once proposed as a basis for secret codes. The best known early scheme, from Ralph Merkle and Martin Hellman in the 1970s, was broken by Adi Shamir in the early 1980s. A problem being hard in the worst case does not make every instance hard, a lesson that matters for one-way functions.
Common questions
Why is it called "0/1"?
Each item's decision variable is 0 (leave it) or 1 (take it), with nothing in between.
Does item order matter in the table?
The final answer does not depend on the order. Intermediate rows and, when ties exist, the particular packing you trace back may differ.
How should I solve a real budgeting choice?
For a modest number of options, a spreadsheet solver or the table method will do. Check first that your values really add up and that choosing one option does not change the worth of another, since the basic model assumes neither interacts.