0/1 Knapsack Problem
The 0/1 Knapsack problem asks: given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, determine the maximum total value that can be carried, where each item can either be fully included or excluded (no fractional items).
Recursive Approach
At every item, decide to either include it (if it fits) or skip it, and take the maximum of both choices. This naive recursion recomputes overlapping subproblems and runs in exponential time.
Dynamic Programming Approach
Build a table dp[i][w] representing the maximum value achievable using the first i items with capacity w. Each cell is computed from smaller subproblems, avoiding recomputation.
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(dp[i - 1][w],
dp[i - 1][w - weights[i - 1]] + values[i - 1])
else:
dp[i][w] = dp[i - 1][w]
return dp[n][capacity]
print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)) # Output: 9
Complexity
| Approach | Time | Space |
|---|---|---|
| Naive Recursion | O(2^n) | O(n) |
| Dynamic Programming | O(n * capacity) | O(n * capacity) |
Applications
- Resource allocation and budgeting problems.
- Cargo loading and shipment optimization.
- Portfolio selection under a fixed investment budget.
Filling the DP Table for the Example
The sample call uses weights [1, 3, 4, 5], values [1, 4, 5, 7] and capacity 7. Each row adds one more item and each column is a capacity from 0 to 7. A cell takes the better of two choices: the value from the row above (skip the item), or the item's value plus the best value from the row above at the leftover capacity (take the item).
| Items allowed | w=0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| + item (1, 1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| + item (3, 4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| + item (4, 5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| + item (5, 7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
Take the cell for the third row at capacity 7. Skipping the weight-4 item gives 5. Taking it leaves capacity 3, where the row above holds 4, so 4 + 5 = 9. The larger value, 9, wins. In the last row, taking the weight-5 item at capacity 7 gives 7 + 1 = 8, which loses to 9, so the answer stays 9.
Finding Which Items Were Picked
The table also tells you the chosen items. Start at the bottom-right cell and move upwards. If a cell differs from the cell above it, that row's item was taken, so subtract its weight and continue from the new capacity.
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):
for w in range(capacity + 1):
dp[i][w] = dp[i - 1][w]
if weights[i - 1] <= w:
dp[i][w] = max(dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1])
chosen, w = [], capacity
for i in range(n, 0, -1):
if dp[i][w] != dp[i - 1][w]:
chosen.append(i - 1)
w -= weights[i - 1]
return dp[n][capacity], chosen[::-1]
print(knapsack_items([1, 3, 4, 5], [1, 4, 5, 7], 7)) # (9, [1, 2])
Indices 1 and 2 are the items with weights 3 and 4. Together they weigh exactly 7 and are worth 9.
Saving Memory With a One-Row Table
Each row only reads the row above it, so a single list is enough. The important detail is to loop over capacity from high to low. Going downwards means dp[w - wt] still holds the value from before this item was considered, so the item cannot be used twice.
def knapsack_1d(weights, values, capacity):
dp = [0] * (capacity + 1)
for wt, val in zip(weights, values):
for w in range(capacity, wt - 1, -1):
dp[w] = max(dp[w], dp[w - wt] + val)
return dp[capacity]
This keeps the same running time but needs memory proportional only to the capacity. The trade-off is that you can no longer trace back the chosen items from the table.
Related Variants and Frequent Errors
- Fractional knapsack: items can be split, so a greedy approach that sorts by value per unit weight gives the optimal answer. Greedy does not work for 0/1.
- Unbounded knapsack: each item can be used any number of times. In the one-row version, simply loop capacity upwards instead of downwards.
- Off-by-one indexing: row i refers to item
i - 1in the input lists. Mixing these up is the most common bug. - Huge capacity: the running time grows with capacity, not just with the number of items. For very large capacities with few items, a different method may be needed.
Interview checklist: define the state, write the include/exclude recurrence, fill a small table by hand, then mention the one-row optimisation.