Sub topic 13
Putting it together: 0/1 knapsack
The 0/1 knapsack problem uses every idea from the earlier chapters at once. You define a two-part state, write a recurrence that chooses between two options, implement it top-down and bottom-up, trace back to find which items were chosen, and shrink the table to one row. The one-row version only works if its loop runs in the right direction.
This chapter assumes you are comfortable with the earlier material: DP state and recurrence, memoization with functools.lru_cache, tabulation fill order, counting states times work per state, traceback through a 2D table, and rolling arrays. It also assumes working Python and Big-O notation.
The problem
You have n items. Item i has a weight weights[i] and a value values[i]. You also have a bag with a weight limit capacity. Pick a subset of items whose total weight is at most capacity, so that their total value is as large as possible. Each item is either taken once or left out. That restriction is the "0/1" in the name.
All weights and the capacity are non-negative integers. That matters later, because the capacity becomes a table index.
Why greedy fails
A natural first idea is to sort items by value per unit of weight and take the best ratios first. Try it on this input:
| Item | Weight | Value | Value / weight |
|---|---|---|---|
| 0 | 1 | 1 | 1.00 |
| 1 | 3 | 4 | 1.33 |
| 2 | 4 | 5 | 1.25 |
| 3 | 5 | 7 | 1.40 |
With capacity 7, greedy takes item 3 (weight 5, value 7). Only 2 units of capacity remain, so it adds item 0, for a total value of 8. The best answer is items 1 and 2: weight 7, value 9. Greedy commits early to a choice that blocks a better combination. DP avoids this by comparing both options at every step.
State, recurrence, and base cases
Taking an item changes two things: which items are still available and how much capacity is left. So the state needs both.
- State:
dp[i][c]is the best total value you can get using only the firstiitems with capacityc. - Recurrence: for item
i - 1with weightwand valuev: - Skip it:
dp[i - 1][c]. - Take it, only if
w <= c:dp[i - 1][c - w] + v. dp[i][c]is the larger of the options that are allowed.- Base cases:
dp[0][c] = 0for everyc, because with no items there is no value. - Answer:
dp[n][capacity].
Both DP properties hold. The problem has optimal substructure: if the best packing for (i, c) takes item i - 1, the rest of that packing must be the best packing for (i - 1, c - w). Otherwise you could swap in a better sub-packing. The problem also has overlapping subproblems: different sequences of take and skip decisions reach the same (i, c). For example, taking a weight-2 item and skipping another weight-2 item leaves the same remaining capacity as doing the reverse.
Top-down with memoization
The recurrence translates directly into a cached recursive function. Here best(i, c) means the same thing as dp[i][c].
from functools import lru_cache
def knapsack_memo(weights, values, capacity):
@lru_cache(maxsize=None)
def best(i, c):
if i == 0:
return 0
w, v = weights[i - 1], values[i - 1]
skip = best(i - 1, c)
if w <= c:
return max(skip, best(i - 1, c - w) + v)
return skip
return best(len(weights), capacity)
print(knapsack_memo([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9The cache key is the pair (i, c). The lists are captured by the closure and are not part of the key, so they never need to be hashable. Defining best inside the outer function also gives each call a fresh cache. A module-level cached function would keep stale results from earlier inputs.
The recursion depth is n + 1. Python's default recursion limit is about 1000, so this version raises RecursionError once you have around a thousand items.
Bottom-up with a full table and traceback
Row i reads only from row i - 1, so filling rows in increasing i is a valid order. Within a row, any order of c works, because no entry reads from its own row.
def knapsack_table(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w, v = weights[i - 1], values[i - 1]
for c in range(capacity + 1):
dp[i][c] = dp[i - 1][c]
if w <= c and dp[i - 1][c - w] + v > dp[i][c]:
dp[i][c] = dp[i - 1][c - w] + v
chosen = []
c = capacity
for i in range(n, 0, -1):
if dp[i][c] != dp[i - 1][c]:
chosen.append(i - 1)
c -= weights[i - 1]
chosen.reverse()
return dp[n][capacity], chosen
print(knapsack_table([1, 3, 4, 5], [1, 4, 5, 7], 7)) # (9, [1, 2])The filled table
Here is the table for the example input. Rows are i and columns are capacities 0 to 7.
| i (item added) | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 0 (none) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 (w1, v1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 2 (w3, v4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| 3 (w4, v5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| 4 (w5, v7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
The traceback starts at dp[4][7] = 9:
dp[4][7] = 9equalsdp[3][7] = 9, so item 3 was skipped.dp[3][7] = 9differs fromdp[2][7] = 5, so item 2 was taken. Capacity drops to 3.dp[2][3] = 4differs fromdp[1][3] = 1, so item 1 was taken. Capacity drops to 0.dp[1][0] = 0equalsdp[0][0], so item 0 was skipped.
The chosen items are 1 and 2, matching the optimal answer found earlier.
Shrinking to one row
Row i depends only on row i - 1, so you can keep a single array and overwrite it in place:
def knapsack(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9The loop runs from capacity down to w. Capacities below w can't take the item, so they keep their old values and the loop skips them.
Why the loop must run downward
When the loop updates dp[c], it reads dp[c - w]. That read must return the value from the previous row, before the current item was considered. With a downward loop, c - w < c has not been visited yet in this pass, so it still holds the old row's value.
With an upward loop, dp[c - w] has already been updated for the current item. The program then lets the same item be taken again. Take one item with weight 2 and value 3, and capacity 4:
| Loop direction | dp after the pass | dp[4] | Meaning |
|---|---|---|---|
| Downward (4, 3, 2) | [0, 0, 3, 3, 3] | 3 | Item used once |
| Upward (2, 3, 4) | [0, 0, 3, 3, 6] | 6 | Item used twice |
The upward version is a correct solution to a different problem, the unbounded knapsack, where each item has unlimited copies. The two programs differ by one range call, and both run without errors, so this bug is easy to miss.
Complexity and the pseudo-polynomial gotcha
There are (n + 1) × (capacity + 1) states, and each takes O(1) work. The cost is:
| Version | Time | Space | Recovers items? |
|---|---|---|---|
| Memoized | O(n × W) worst case | O(n × W) cache plus O(n) stack | Yes, by re-walking the cache |
| Full table | O(n × W) | O(n × W) | Yes |
| One row | O(n × W) | O(W) | No |
Here W is capacity. O(n × W) looks polynomial, but W is a numeric value, not an input length. Writing down a capacity of one billion takes about 30 bits, yet the table would have a billion columns. The running time grows exponentially in the number of bits of W, so the algorithm is called pseudo-polynomial. 0/1 knapsack is NP-hard, and this DP does not contradict that. It is fast only when W is small.
Choosing an implementation
The decision criteria from the earlier chapter apply directly:
- Small capacity, need the items: use the full table with traceback. It is predictable and has no recursion limit.
- Small capacity, value only: use the one-row version. It is the fastest in practice and uses O(W) memory.
- Huge capacity, few items: use memoization. It visits only reachable
(i, c)pairs, and there are at most 2^n of them no matter how largeWis. With 25 items and a capacity of 10^9, a table is impossible, but the memoized version touches at most about 33 million states and usually far fewer. - Many items (over about 1000): avoid plain recursion, or raise the limit with
sys.setrecursionlimitand accept the risk of crashing the interpreter's C stack.
Edge cases
- Capacity 0: every version returns 0. The one-row loop runs only for items of weight 0.
- Weight-0 items: the downward loop still visits each
conce per item, so the item is added at most once. That is correct. - No items:
zipyields nothing,dp[capacity]stays 0, and the table versions return(0, []). - Negative weights: the state definition breaks, because
c - wwould exceedcapacity. Reject them at input. - Non-integer weights: you can't index a list with them. Scale to integers if precision allows, or switch to a value-indexed DP that stores the minimum weight for each total value.
Exercise
Change the one-row knapsack so it solves the unbounded version, where each item can be taken any number of times. What is the answer for weights [2, 3], values [3, 5], capacity 7?
Show answer
Run the inner loop upward: for c in range(w, capacity + 1): with the same update dp[c] = max(dp[c], dp[c - w] + v). Reading the already-updated dp[c - w] lets an item be reused. For the input, the best is one weight-2 item plus one weight-3 item (weight 5, value 8), or two weight-2 items plus one weight-3 item (weight 7, value 11). The answer is 11.
Exercise
Using the filled table in this chapter, what is the best value with capacity 6, and which items achieve it? Trace back from dp[4][6].
Show answer
dp[4][6] = 8. It differs from dp[3][6] = 6, so item 3 (weight 5) is taken and capacity drops to 1. dp[3][1] = 1 equals dp[2][1] = 1, so item 2 is skipped. dp[2][1] = 1 equals dp[1][1] = 1, so item 1 is skipped. dp[1][1] = 1 differs from dp[0][1] = 0, so item 0 is taken. The items are 0 and 3, with weight 6 and value 8.
Exercise
You have 30 items and a capacity of 2,000,000,000. Which implementation should you choose, and why?
Show answer
Memoization. A table would need about 2 billion columns per row, which is far too much memory. The memoized version visits only reachable (i, c) states, at most 2^30 in theory but usually far fewer in practice. Its recursion depth is only 31, so the recursion limit is not a concern. If the reachable states still turn out to be too many, use a different technique, such as meet-in-the-middle.