Sub topic 10
0/1 knapsack: recurrence, table, and space reduction
This chapter assumes you know Big-O notation, can read Python, and have seen the idea of overlapping subproblems from the dynamic programming chapters.
The problem
You have n items. Item i has a weight w[i] and a value v[i]. A bag holds total weight at most W. For each item you choose to take it whole or leave it. You cannot split it and cannot take it twice. That is the "0/1" in the name. The goal is the maximum total value.
Greedy by value-to-weight ratio is correct for the fractional version but fails here. Take items (weight, value) = (10, 60), (20, 100), (30, 120) with W = 50. Ratio order takes the first two items for a value of 160. The best choice is the last two items, for 220. Because the choices interact through the shared capacity, we use dynamic programming.
The recurrence
Let dp[i][c] be the best value using only the first i items with capacity c. Item i is either skipped or taken:
- Skip it:
dp[i-1][c]. - Take it (only if
w[i] <= c):dp[i-1][c - w[i]] + v[i].
dp[i][c] = dp[i-1][c] if w[i] > c
dp[i][c] = max(dp[i-1][c], dp[i-1][c - w[i]] + v[i]) otherwiseThe base cases are dp[0][c] = 0 for every c (no items) and dp[i][0] = 0 (no capacity, assuming positive weights). Optimal substructure holds because the best answer for (i, c) contains a best answer for a smaller subproblem. Subproblems overlap because many different choice sequences reach the same (i, c) pair.
Filling the table
Rows go from 1 to n. Within a row, any column order works, because row i reads only row i-1. The table has (n+1)(W+1) cells and each costs O(1), so time is O(nW) and space is O(nW).
Here is the table for weights [1, 3, 4, 5], values [1, 4, 5, 7], and W = 7.
| Items used | c=0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| item 1 (1, 1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| item 2 (3, 4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| item 3 (4, 5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| item 4 (5, 7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
Check one cell. For item 3 at c = 7: skip gives 5, and take gives dp[2][3] + 5 = 4 + 5 = 9. So the cell holds 9.
Recovering the chosen items
The table gives only the best value. To find which items were taken, walk backward from dp[n][W]. If dp[i][c] != dp[i-1][c], item i was taken, so subtract its weight from c.
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 c >= w:
dp[i][c] = max(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 indices [1, 2] are items with weights 3 and 4, which total 7 and have value 4 + 5 = 9.
Reducing space to O(W)
Row i uses only row i-1, so one array is enough if you update it in the right order. Loop the capacity downward, so that dp[c - w] still holds the previous row's value when you read it.
def knapsack_01(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_01([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9Time stays O(nW), and space drops to O(W). The cost is that you can no longer trace back the chosen items from this array alone.
Edge cases and complexity notes
- If
w[i] > W, the item never fits. The looprange(capacity, w - 1, -1)is empty, so it is skipped safely. - If W = 0, the answer is 0 for positive weights.
- Zero-weight items with positive value are always taken. The downward loop handles them correctly, because
dp[c - 0] + vreads the olddp[c]before it is overwritten. - O(nW) is pseudo-polynomial. The running time depends on the numeric value of W, not on the number of bits needed to write it. If W is 2^k, the work is exponential in the input length. The problem is NP-hard, and no contradiction arises.
- Memoized recursion visits only reachable states. It can be faster when few (i, c) pairs are needed, but it uses recursion depth n and often a hash table.
Exercises
Exercise
Items have weights [2, 3, 4] and values [3, 4, 6]. Capacity is 5. Fill the dp table and give the maximum value and the items chosen.
Show answer
Row 0: 0 0 0 0 0 0. After item 1 (2, 3): 0 0 3 3 3 3. After item 2 (3, 4): 0 0 3 4 4 7. After item 3 (4, 6): 0 0 3 4 6 7. The maximum value is dp[3][5] = 7. Trace back: dp[3][5] equals dp[2][5], so item 3 is skipped. dp[2][5] = 7 differs from dp[1][5] = 3, so item 2 is taken and c becomes 2. dp[1][2] = 3 differs from dp[0][2] = 0, so item 1 is taken. The chosen items are 1 and 2, with weight 5 and value 7.
Exercise
A 0/1 knapsack has n = 100 items and capacity W = 1000. State the time and space of the 2D table and of the 1D version. Then explain why O(nW) does not make the problem polynomial.
Show answer
The 2D table takes O(nW) = about 100,000 cell updates and O(nW) space. The 1D version takes the same time and O(W) space. O(nW) is pseudo-polynomial because W is a number, and its size as input is only log W bits. Doubling the number of bits in W squares its value, so the running time grows exponentially in the input length.