0/1 knapsack
medium 22 minPack items with weights and values into a bag of capacity W to get the most value, each item taken whole or not at all.
Video lesson · Chapter 1 of 8
The field kit
0/1 knapsack in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
Take or leave each item. Leave it: dp[i - 1][w]. Take it if it fits: value + dp[i - 1][w - weight]
Understand it
Start here
The problem: a bag with a weight limit
You have items, item with weight and value , and a bag that holds at most . Choose items to maximise the total value without going over . Each item is taken whole or left behind: 0 or 1, never half a tent and never two of the same item. The camping trip below has capacity 7 and the best load is worth 9.
The camping trip, capacity 7
| Item | Weight | Value | Value per kg | In the best load? |
|---|---|---|---|---|
| Water bottle | 1 | 1 | 1.00 | no |
| Sleeping bag | 3 | 4 | 1.33 | yes |
| Tent | 4 | 5 | 1.25 | yes |
| Camping stove | 5 | 7 | 1.40 | no |
What this topic builds on
DP core
State, recurrence, base case, fill order. Recapped in Dynamic programming: the core idea; here the state has two numbers.
Subsets
Every load is a subset of the items, of them. Subsets lists them all; knapsack picks the best one without listing.
Take or skip
The same binary choice as House robber, with a capacity that shrinks when you take.
Why simple rules fail
Greedy by value per kilo
The natural shortcut: sort by and pack the best ratios first. On the camping trip that packs the stove (1.40, 5 kg), finds that the bag (3 kg) and tent (4 kg) no longer fit in the 2 kg left, adds the bottle, and stops at 8. The bag and tent together give 9. Taking the stove early wasted room that nothing else could fill.
Fractional knapsack: greedy works
- Items can be cut, like gold dust or bandwidth.
- Take the best ratios whole, then a fraction of the next one.
- Camping trip: stove plus 2/3 of the bag, .
- for the sort.
0/1 knapsack: greedy fails
- Items are whole: a gap left by a big item may stay empty.
- Camping trip: greedy 8, best 9.
- Capacity 50 with (10, 60), (20, 100), (30, 120): greedy 160, best 220.
- Needs the DP table (or search).
The fractional optimum is an upper bound
Brute force
The take-or-skip tree
Define as the best value from the first $i$ items with $c$ units of room. For item : leave it and the answer is ; take it (only if ) and the answer is . Below, three day-hike items: snacks (1, 2), first aid (2, 5), camera (2, 4), capacity 4.
Calls made by f(3, 4)
def knapsack_brute(weights, values, W): def best(i, cap): if i == 0: return 0 # no items left wt, val = weights[i - 1], values[i - 1] skip = best(i - 1, cap) # leave item i if wt > cap: return skip # does not fit return max(skip, val + best(i - 1, cap - wt)) return best(len(weights), W)print(knapsack_brute([1, 2, 2], [2, 5, 4], 4)) # 9print(knapsack_brute([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9Paths against states
Fix 1
Memoise on (i, cap)
One memoised call
def knapsack_memo(weights, values, W): memo = {} def best(i, cap): if i == 0: return 0 if (i, cap) in memo: return memo[(i, cap)] wt, val = weights[i - 1], values[i - 1] res = best(i - 1, cap) if wt <= cap: res = max(res, val + best(i - 1, cap - wt)) memo[(i, cap)] = res return res return best(len(weights), W)print(knapsack_memo([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9print(knapsack_memo([2, 3, 4, 5, 3], [3, 5, 6, 8, 4], 10)) # 16Cost of the memoised version
The recurrence
dp[i][w] = max(leave, take)
Best value from the first i items with room w
Filling one cell
Why it is right. Take the best load for the first items and room . Either it leaves item , and then it is a load for the first items within , worth at most dp[i-1][w]. Or it packs item , and the rest is a load for the first items within , worth at most dp[i-1][w - w_i]. Both are reachable, so the best is their max: optimal substructure. Using row in the take option is what stops item being packed twice.
Fix 2
Fill the table: the camping trip
dp[i][w] for capacity 7
| Items so far | w=0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| + bottle (1, 1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| + bag (3, 4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| + tent (4, 5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| + stove (5, 7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
dp[2][4] = max(dp[1][4], 4 + dp[1][1]) = max(1, 5) = 5: bag and bottle. dp[3][7] = max(5, 5 + dp[2][3]) = 9: tent and bag. In the last row the stove gives 7 + dp[3][2] = 8 and loses to 9.def knapsack(weights, values, W): n = len(weights) dp = [[0] * (W + 1) for _ in range(n + 1)] for i in range(1, n + 1): wt, val = weights[i - 1], values[i - 1] for w in range(W + 1): dp[i][w] = dp[i - 1][w] # leave item i if wt <= w: dp[i][w] = max(dp[i][w], val + dp[i - 1][w - wt]) return dp[n][W]print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9 camping tripprint(knapsack([1, 2, 2, 3], [2, 5, 4, 3], 5)) # 11 day hikeprint(knapsack([2, 3, 4, 5, 3], [3, 5, 6, 8, 4], 10)) # 16 mountain expedition- 1Itemsweights, values, W
- 2Row 0all zeros
- 3Each cellmax(leave, take)
- 4Cornerdp[n][W] = 9
- 5Walk backbag + tent
Reconstruction
Which items were packed?
Walking up from the corner
The walk on the camping table
| Row | w | dp[i][w] | dp[i-1][w] | Decision | Room after |
|---|---|---|---|---|---|
| 4 stove | 7 | 9 | 9 | left | 7 |
| 3 tent | 7 | 9 | 5 | packed | 7 - 4 = 3 |
| 2 bag | 3 | 4 | 1 | packed | 3 - 3 = 0 |
| 1 bottle | 0 | 0 | 0 | left | 0 |
def knapsack_items(weights, values, W): n = len(weights) dp = [[0] * (W + 1) for _ in range(n + 1)] for i in range(1, n + 1): wt, val = weights[i - 1], values[i - 1] for w in range(W + 1): dp[i][w] = dp[i - 1][w] if wt <= w: dp[i][w] = max(dp[i][w], val + dp[i - 1][w - wt]) picked, w = [], W for i in range(n, 0, -1): if dp[i][w] != dp[i - 1][w]: picked.append(i - 1) w -= weights[i - 1] return dp[n][W], picked[::-1]names = ["bottle", "bag", "tent", "stove"]best, idx = knapsack_items([1, 3, 4, 5], [1, 4, 5, 7], 7)print(best, [names[k] for k in idx]) # 9 ['bag', 'tent']Fix 3
One row, swept right to left
Row reads only row , so keep one array dp of length and overwrite it item by item. The catch is the read dp[w - wt]: it must still hold the previous item's row. Sweep from down to and every smaller index is untouched when you read it.
def knapsack_1d(weights, values, W): dp = [0] * (W + 1) for wt, val in zip(weights, values): for w in range(W, wt - 1, -1): # right to left dp[w] = max(dp[w], val + dp[w - wt]) return dp[W]def knapsack_forward(weights, values, W): # WRONG for 0/1 dp = [0] * (W + 1) for wt, val in zip(weights, values): for w in range(wt, W + 1): # left to right dp[w] = max(dp[w], val + dp[w - wt]) return dp[W]print(knapsack_1d([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9print(knapsack_forward([1], [1], 7)) # 7: one bottle packed 7 timesWhy the direction decides the problem
One row
- space: 8 cells instead of 40 on the camping trip.
- Shortest code, the usual interview answer.
- Loop stops at : smaller capacities keep their values.
Full 2D table
- space.
- Easier to explain and to debug cell by cell.
- But keep it when you must list the packed items.
Complexity
O(n·W): pseudo-polynomial
Time and space
max per cell. With the single row, space depends only on the capacity.Why it is not truly polynomial
Every approach
| Approach | Time | Space | Use it when |
|---|---|---|---|
| Brute-force take or skip | stack | n is tiny (about 20 or fewer) | |
| Memo on (i, cap) | Quick to write from the recurrence; touches only reachable states | ||
| 2D table | You need the list of items | ||
| One row, right to left | Only the best value is needed | ||
| Greedy by ratio | Only for fractional knapsack |
Variants
Subset sum, partition, target sum
| Problem | Item weight | Cell holds | Update (right to left) |
|---|---|---|---|
| 0/1 knapsack | best value | dp[w] = max(dp[w], v + dp[w - wt]) | |
| Subset sum to T | the number | reachable? True/False | ok[s] = ok[s] or ok[s - x] |
| Partition equal subset sum | the number | reachable? | subset sum with ; odd is False |
| Count subsets with sum T | the number | number of ways | ways[s] += ways[s - x] |
| Target sum (+/- signs) | the number | number of ways | count subsets to |
| Last stone weight II | the number | reachable? | largest reachable ; answer |
Target sum reduces to counting subsets
[1, 1, 1, 1, 1] and : count subsets summing to 4, which is 5.def can_partition(nums): total = sum(nums) if total % 2: return False target = total // 2 ok = [True] + [False] * target for x in nums: for s in range(target, x - 1, -1): ok[s] = ok[s] or ok[s - x] return ok[target]def target_sum_ways(nums, target): S = sum(nums) if abs(target) > S or (S + target) % 2: return 0 P = (S + target) // 2 ways = [1] + [0] * P for x in nums: for s in range(P, x - 1, -1): ways[s] += ways[s - x] return ways[P]print(can_partition([2, 3, 4, 5]), can_partition([1, 2, 3, 5])) # True Falseprint(target_sum_ways([1, 1, 1, 1, 1], 3)) # 5Spotting the pattern
Recap
Key takeaways
Key points
- dp[i][w] is the best value from the first i items with room w; the answer is dp[n][W].
- Leave item i: dp[i-1][w]. Take it only if it fits: value + dp[i-1][w - weight]. Keep the max.
- The take option reads row i-1, so each item is used at most once.
- Greedy by value per kilo fails for 0/1 (camping trip: 8 vs 9) and is only right for fractional knapsack.
- Brute force is O(2^n); memo on (i, cap) or the table is O(n·W), pseudo-polynomial in W.
- Walk back from the corner: changed means packed (subtract its weight), equal means left.
- One row swept right to left gives O(W) space; sweeping left to right solves the unbounded knapsack instead.
- Subset sum, partition and target sum are the same loop with or, or with +=.