The 0/1 knapsack: choosing items under a limit
Pick items with a weight and a value to get the most value without exceeding a capacity. The table, the 1D trick, and the many interview problems that are knapsack in disguise.
In short
For each item you decide take it or leave it (once). Let dp[c] be the best value with capacity c; for each item, update c from high to low: dp[c] = max(dp[c], dp[c − w] + v). Time O(n · W), space O(W).
The idea: two choices per item
A bag holds 5 kg. Items weigh and are worth different amounts. The best choice for the first i items with capacity c is either skip item i (the best for the first i−1 items) or take it (its value plus the best for i−1 items with capacity c − weight).
items (weight → value)
1def knapsack(weights, values, cap):2 dp = [0] * (cap + 1)3 for i in range(len(weights)):4 for c in range(cap, weights[i] - 1, -1):5 dp[c] = max(dp[c], dp[c - weights[i]] + values[i])6 return dp[cap]
Variables
The 1D trick: go downwards
The full table is dp[i][c], but row i only reads row i−1, so a single array is enough, if you loop the capacity downwards. Then dp[c − w] still holds the value from before this item, so the item is counted at most once.
0/1 knapsack
- Each item once
- Capacity loop goes down
- Example: partition, subset sum
Unbounded knapsack
- Each item any number of times
- Capacity loop goes up
- Example: coin change
Knapsack in disguise
| Problem | "Capacity" | "Value" |
|---|---|---|
| Subset sum / can you reach exactly S? | The target sum S | true / false |
| Partition into two equal halves | Half of the total sum | true / false |
| Maximum loot within a budget | Budget | Sum of values |
| Number of ways to reach a target | Target | Count (add instead of max) |
Key takeaways
- 01Per item: skip it, or take it and add its value to the best of the remaining capacity.
- 02A single dp array works if the capacity loop goes from high to low.
- 03Loop upwards instead and you get the unbounded version (coin change).
- 04Subset sum and partition are the same table with true/false.
Check your understanding
1 of 3
In the 0/1 knapsack, what are the two options for an item?
Related topics
1D dynamic programming
If a recursive solution solves the same subproblem many times, store each answer once. Define dp[i] (what it means), write how it depends on smaller entries, fill it from the base case up. Time = number of states × work per state.
10 min read →2D dynamic programming
If one index isn't enough to describe the subproblem, use two: `dp[i][j]`. Typical for grids and for problems on two strings or arrays. The table has m × n cells, each filled from its neighbours in O(1).
9 min read →Subsets & combinations
When a problem asks for all the ways to do something, walk a tree of choices with recursion: choose → explore → undo. For subsets each number is either in or out, so the tree has 2ⁿ leaves.
9 min read →