Sub topic 7
0/1 Knapsack: Recurrence, Table, and Space Reduction
Assume you know Big-O notation, arrays, loops, and basic recurrence definitions. You should also know that a knapsack has a capacity, and each item has a weight and a value.
In the 0/1 knapsack problem, each item can be chosen once or rejected. The name “0/1” means the decision for an item is either 0, not chosen, or 1, chosen. The goal is to maximize total value without exceeding the capacity.
State and recurrence
Let dp[i][c] be the maximum value obtainable using the first i items with capacity c.
For item i, there are two choices:
- Reject it. The value is
dp[i - 1][c]. - Choose it, if its weight
w[i]fits. The value isdp[i - 1][c - w[i]] + v[i].
Therefore:
- If
w[i] > c, thendp[i][c] = dp[i - 1][c]. - Otherwise:
dp[i][c] = max(dp[i - 1][c],
dp[i - 1][c - w[i]] + v[i])The second term uses row i - 1. This is important: it prevents choosing the same item again.
The base cases are:
dp[0][c] = 0: no items give value zero.dp[i][0] = 0: zero capacity allows no item.
Filling the table
Consider weights [1, 3, 4, 5], values [1, 4, 5, 7], and capacity 7.
| Items considered | Capacity 0 | Capacity 1 | Capacity 2 | Capacity 3 | Capacity 4 | Capacity 5 | Capacity 6 | Capacity 7 |
|---|---|---|---|---|---|---|---|---|
| None | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Weight 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| Weights 1, 3 | 0 | 1 | 1 | 4 | 4 | 5 | 5 | 5 |
| Weights 1, 3, 4 | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
The final answer is 9, achieved by choosing weights 3 and 4, with values 4 and 5.
One-dimensional space reduction
A full table uses O(nW) space for n items and capacity W. Each row depends only on the previous row, so we can keep one array:
def knapsack_01(weights, values, capacity):
dp = [0] * (capacity + 1)
for weight, value in zip(weights, values):
for current_capacity in range(capacity, weight - 1, -1):
dp[current_capacity] = max(
dp[current_capacity],
dp[current_capacity - weight] + value
)
return dp[capacity]
print(knapsack_01([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9The capacity loop runs downward. When processing an item of weight weight, dp[current_capacity - weight] must still describe the previous item set. If the loop runs upward, an updated value can be reused in the same iteration, incorrectly allowing the item multiple times.
The time complexity is O(nW). The one-dimensional version uses O(W) space.
Exercise
Why must the capacity loop run from capacity down to weight in the one-dimensional algorithm?
Show answer
Descending order ensures that dp[c - weight] still represents a state from before the current item was processed, so the item cannot be chosen more than once.