Sub topic 13
Putting it together: 0/1 knapsack
This chapter assumes you can already define a DP state and recurrence, fill a two-dimensional table, trace back through it, and shrink a table to a rolling array. The 0/1 knapsack problem uses all four of those skills.
The problem
You have n items. Item i has a weight weights[i] and a value values[i]. Your bag holds at most capacity units of weight. You choose a set of items that maximizes total value without going over capacity. Each item is taken whole or left behind, and you can take it at most once. The "0/1" in the name means exactly that.
Greedy rules such as "take the best value-per-weight first" fail on this problem. With weights [1, 3, 4, 5], values [1, 4, 5, 7], and capacity 7, the greedy choice starts with the weight-5 item (ratio 1.4) and reaches only 8. The best answer is 9, from the items of weight 3 and 4.
State, recurrence, base cases
- State:
dp[i][c]is the best value you can get from the firstiitems with capacityc. - Recurrence: for item
iyou either skip it or take it. - Skip:
dp[i-1][c] - Take (only if
w <= c):dp[i-1][c-w] + v dp[i][c]is the larger of the two.- Base cases:
dp[0][c] = 0for everyc, because no items means no value.
Optimal substructure holds: if the best solution takes item i, the rest of it must be the best solution for the first i-1 items with capacity c-w.
Full table with reconstruction
The 2D table keeps every row, which lets you trace back which items were chosen. If dp[i][c] differs from dp[i-1][c], item i must have been taken.
def knapsack_items(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]
return dp[n][capacity], sorted(chosen)
print(knapsack_items([1, 3, 4, 5], [1, 4, 5, 7], 7)) # (9, [1, 2])The trace-back starts at dp[4][7] = 9. That equals dp[3][7], so the weight-5 item was skipped. dp[3][7] = 9 differs from dp[2][7] = 5, so the weight-4 item was taken and capacity drops to 3. dp[2][3] = 4 differs from dp[1][3] = 1, so the weight-3 item was taken and capacity drops to 0.
One row is enough for the value
Row i reads only from row i-1. When you need only the value, you can keep a single row 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 capacity loop has to run downward. When you update dp[c], you read dp[c - w], which sits at a smaller index. Going downward means that cell has not been overwritten yet, so it still holds the previous row's value. Going upward would read a value that already includes the current item, so one item could be counted more than once.
Cost and choices
| Version | Time | Space | Recovers items? |
|---|---|---|---|
| 2D table | O(n · W) | O(n · W) | Yes |
| 1D rolling row | O(n · W) | O(W) | No |
| Memoized `lru_cache` on `(i, c)` | O(n · W) worst case | O(n · W) plus recursion depth n | With extra work |
Here W is the capacity. The runtime is called pseudo-polynomial because it grows with the numeric value of W, not with the number of bits needed to write it. With a capacity of 10⁹, the table approach is impractical. Memoization can help when only a few (i, c) pairs are reachable, for example when there are few items and the weights are large and irregular.
Exercise
Change the inner loop of knapsack to for c in range(w, capacity + 1): and call it with weights [2], values [3], capacity 4. What does it return, and why is that wrong for 0/1 knapsack?
Show answer
It returns 6. At c = 2, dp[2] becomes 3. At c = 4, it reads the already-updated dp[2] and sets dp[4] = 3 + 3 = 6, so the single item was taken twice. The correct 0/1 answer is 3.
Exercise
In the trace-back of knapsack_items, why is it valid to conclude that item i was taken when dp[i][c] != dp[i-1][c]?
Show answer
The recurrence gives dp[i][c] exactly two options: dp[i-1][c] (skip) or dp[i-1][c-w] + v (take). If the stored value differs from the skip option, it must have come from the take option.