Knapsack problems
The 0-1 knapsack problem asks which items, each with a weight and a value, to take for the most value within a capacity; dynamic programming fills an (n + 1) × (capacity + 1) table where each cell decides whether to take the item or leave it.
A knapsack holds at most 6 kg. A book weighs 2 and is worth 3, a camera weighs 3 and is worth 4, a laptop weighs 4 and is worth 5. Taking the highest value per kilo first (last lesson's greedy idea) takes the book (1.5), then the camera (1.33): 5 kg, worth 7, and nothing fits in the last kilo; yet the book and the laptop make exactly 6 kg and are worth 8. Greedy is wrong here. Brute force gets it right: take or leave each item, 2ⁿ ways for n items, 4096 for 12, a billion for 30. The 0-1 knapsack (each item taken at most once) is the classic dynamic programming problem: its table is only "items × capacity" in size, and each box asks one question, "take this item or leave it". Coin change, partitioning into equal sums, target sum… a whole family of problems are this one in disguise.
A 2D table: take it or leave it
The four steps from the last lesson:
- State:
dp[i][c]= the most value from the first i items with capacity c. - Transition: item i (weight w, value v) is either left, and the answer is the same as for the first i − 1:
dp[i-1][c]; or taken (if w ≤ c): make room for w and give the remaining capacity c − w to the first i − 1 items:dp[i-1][c-w] + v. Take the larger. - Base case: with no items (i = 0) or no capacity, the value is 0.
- Order: each box reads only the row above, so fill row by row.
1def knapsack(items, cap):2 n = len(items)3 dp = [[0] * (cap + 1) for _ in range(n + 1)] # row 0 and column 0 are all 04 for i in range(1, n + 1):5 w, v = items[i - 1] # item i: row i of the table, index i - 1 in the list6 for c in range(cap + 1):7 dp[i][c] = dp[i - 1][c] # leave it8 if w <= c:9 dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v) # take it10 return dp11 12items = [(2, 3), (3, 4), (4, 5)] # (weight, value): book, camera, laptop13dp = knapsack(items, 6)14for row in dp:15 print(row)16print("best", dp[-1][-1])
[0, 0, 0, 0, 0, 0, 0] [0, 0, 3, 3, 3, 3, 3] [0, 0, 3, 4, 4, 7, 7] [0, 0, 3, 4, 5, 7, 8] best 8
Compare the work against brute force. 12 items, capacity 20: brute force adds up all 4096 ways of choosing, one by one, while the table has only 13 × 21 boxes:
1def knapsack(items, cap):2 n = len(items)3 dp = [[0] * (cap + 1) for _ in range(n + 1)]4 for i in range(1, n + 1):5 w, v = items[i - 1]6 for c in range(cap + 1):7 dp[i][c] = dp[i - 1][c]8 if w <= c:9 dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)10 return dp[n][cap]11 12def brute(items, cap):13 best, tried = 0, 014 n = len(items)15 for mask in range(1 << n): # each bit: take this item or not16 tried += 117 w = v = 018 for i in range(n):19 if mask >> i & 1:20 w += items[i][0]21 v += items[i][1]22 if w <= cap:23 best = max(best, v)24 return best, tried25 26big = [(3, 4), (4, 5), (5, 7), (2, 3), (6, 8), (7, 9),27 (1, 1), (8, 11), (4, 6), (5, 6), (3, 4), (6, 7)]28value, tried = brute(big, 20)29print(f"brute force: best {value}, {tried} ways tried")30print(f"table: best {knapsack(big, 20)}, {13 * 21} boxes")
brute force: best 28, 4096 ways tried table: best 28, 273 boxes
The time is O(n × W), W the capacity. Note that it grows with the capacity's numeric value: with a capacity of 10⁹ the table cannot be filled, and the 0-1 knapsack becomes a hard problem again (build the table by value instead, or backtrack with pruning).
Try one box yourself: capacity 4, three items (weight 1 value 2) (weight 2 value 3) (weight 3 value 4), and the table filled in up to its last box.
What goes in the question-mark box, dp[3][4] (the first 3 items, capacity 4)?
With n = 100 items and capacity W = 1000, roughly how many boxes does the 2D table have?
Reading back: which items were taken
The table records only "the most", not "what was taken". But you can walk back from the bottom-right corner: if dp[i][c] equals dp[i-1][c] straight above, item i could be left and the value still reached, so move up; if not, item i must have been taken: note it, subtract its weight from the capacity, and move up.
1def knapsack(items, cap):2 n = len(items)3 dp = [[0] * (cap + 1) for _ in range(n + 1)]4 for i in range(1, n + 1):5 w, v = items[i - 1]6 for c in range(cap + 1):7 dp[i][c] = dp[i - 1][c]8 if w <= c:9 dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)10 return dp11 12def taken(items, dp, cap):13 picked = []14 c = cap15 for i in range(len(items), 0, -1): # from the last row up16 if dp[i][c] != dp[i - 1][c]: # different from above: item i was taken17 picked.append(i - 1)18 c -= items[i - 1][0]19 return picked[::-1]20 21items = [(2, 3), (3, 4), (4, 5)]22names = ["book", "camera", "laptop"]23dp = knapsack(items, 6)24print([names[i] for i in taken(items, dp, 6)])25print([names[i] for i in taken(items, dp, 5)])
['book', 'laptop'] ['book', 'camera']
Reading back needs the whole 2D table, so when you need "which items", you cannot shrink it to one row (or you keep a second table of "taken in this box or not").
Three items (weight 1 value 2) (weight 2 value 3) (weight 3 value 4), capacity 5. After filling the table and reading back, what does it print? (Numbered from 0.)
1def knapsack(items, cap):2 n = len(items)3 dp = [[0] * (cap + 1) for _ in range(n + 1)]4 for i in range(1, n + 1):5 w, v = items[i - 1]6 for c in range(cap + 1):7 dp[i][c] = dp[i - 1][c]8 if w <= c:9 dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)10 return dp11 12def taken(items, dp, cap):13 picked = []14 c = cap15 for i in range(len(items), 0, -1):16 if dp[i][c] != dp[i - 1][c]:17 picked.append(i - 1)18 c -= items[i - 1][0]19 return picked[::-1]20 21items = [(1, 2), (2, 3), (3, 4)]22dp = knapsack(items, 5)23print(dp[3][5], taken(items, dp, 5))
Fill in the test for reading back: different from the box straight above means this item was taken. The program prints the numbers of the items taken (book, camera, laptop are 0, 1, 2).
1def knapsack(items, cap):2 n = len(items)3 dp = [[0] * (cap + 1) for _ in range(n + 1)]4 for i in range(1, n + 1):5 w, v = items[i - 1]6 for c in range(cap + 1):7 dp[i][c] = dp[i - 1][c]8 if w <= c:9 dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)10 return dp11 12def taken(items, dp, cap):13 picked = []14 c = cap15 for i in range(len(items), 0, -1):16 if dp[i][c] dp[i - 1][c]:17 picked.append(i - 1)18 c -= items[i - 1][0]19 return picked[::-1]20 21items = [(2, 3), (3, 4), (4, 5)]22dp = knapsack(items, 6)23print(taken(items, dp, 6))
>= every box qualifies (each is at least as big as the one above), so all three count as taken; == is exactly backwards; < is never true, so nothing is taken.One list: run backwards
When only the best value is needed, each row of the 2D table uses only the row above, so a single list dp[c] will do: before item i it holds row i − 1; after the update, it is row i. The catch is the direction of the inner loop.
The dp[c - w] read by dp[c] = max(dp[c], dp[c - w] + v) must still be from the row above (before item i was considered). Going from small capacities up, dp[c - w] has already been updated in this pass and may already contain item i, so adding it again takes the same item twice. Going from large down, dp[c - w] is to the left of c, not reached yet, still old.
With all three items, what does going forwards give?
The same book, camera and laptop, capacity 6, one list with the inner loop going from small to large. What does it print?
1items = [(2, 3), (3, 4), (4, 5)]2dp = [0] * 73for w, v in items:4 for c in range(w, 7): # forwards5 dp[c] = max(dp[c], dp[c - w] + v)6print(dp[6])
dp[c - w] may already contain this item, so every item can be taken any number of times: three books weigh 6 and are worth 9, more than the book and laptop's 8. That is the answer to the unbounded knapsack, not the 0-1 knapsack. 12 would need three cameras, but three cameras weigh 9 and do not fit.1def knapsack_1d(items, cap):2 dp = [0] * (cap + 1)3 for w, v in items:4 for c in range(cap, w - 1, -1): # backwards: each item at most once5 dp[c] = max(dp[c], dp[c - w] + v)6 return dp7 8def wrong_forward(items, cap):9 dp = [0] * (cap + 1)10 for w, v in items:11 for c in range(w, cap + 1): # forwards: an item can be taken many times12 dp[c] = max(dp[c], dp[c - w] + v)13 return dp14 15items = [(2, 3), (3, 4), (4, 5)]16print(knapsack_1d(items, 6))17print(wrong_forward(items, 6))18print(knapsack_1d([(2, 3)], 6), wrong_forward([(2, 3)], 6))
[0, 0, 3, 4, 5, 7, 8] [0, 0, 3, 4, 6, 7, 9] [0, 0, 3, 3, 3, 3, 3] [0, 0, 3, 3, 6, 6, 9]
The backwards one-list version ends up exactly equal to the 2D table's last row, with space down from O(n × W) to O(W). range(cap, w - 1, -1) stops at w: capacities below w cannot hold this item, and keeping the old value there is "leave it".
0-1 knapsack with a one-dimensional list: pick what goes into range(...) so each item is taken at most once and it prints 8.
1def knapsack_1d(items, cap):2 dp = [0] * (cap + 1)3 for w, v in items:4 for c in range():5 dp[c] = max(dp[c], dp[c - w] + v)6 return dp7 8print(knapsack_1d([(2, 3), (3, 4), (4, 5)], 6)[6])
range(cap, w - 1, -1) is cap, cap − 1, … down to w, large to small, so every dp[c − w] it reads is still the value from before this item. w, cap + 1 goes forwards, so an item can be taken several times: 9; cap, w, -1 misses the box c = w, so the book on its own is lost: 7; w - 1, cap reads dp[-1] (the list's last box) and everything goes wrong.Split into two equal halves
✓Complete can_partition(nums): can nums be split into two groups with equal sums? It is a 0-1 knapsack: can some of the numbers make exactly half the total? dp[s] says whether s can be made; one list, backwards.
True False True False
1def can_partition(nums):2 total = sum(nums)3 if total % 2 == 1:4 return False5 target = total // 26 dp = [True] + [False] * target # choosing nothing makes 07 for x in nums:8 # s from target down to x: dp[s] becomes dp[s] or dp[s - x]9 pass10 return dp[target]11 12print(can_partition([1, 5, 11, 5]))13print(can_partition([1, 2, 3, 5]))14print(can_partition([2, 2]), can_partition([3]))
The unbounded knapsack and coin change
The "mistake" from the previous stage (the one-dimensional list walked forwards) is the right answer to another problem: the unbounded knapsack, where every kind of item can be taken any number of times. The transition becomes "after taking this item you may take it again", that is, read dp[c - w] from this row, already updated: the inner loop goes forwards. The 0-1 and unbounded knapsacks differ only in the direction of the loop.
Coin change is an unbounded knapsack: every coin comes in unlimited supply. Last lesson's greedy failure, "1, 3, 4 making 6", comes out exactly right here:
- The fewest coins:
dp[a]= the fewest coins making a,dp[0] = 0, every other entry infinity at first,float("inf")(cannot be made);dp[a] = min(dp[a], dp[a - c] + 1). - The number of ways:
dp[a]= the number of ways to make a,dp[0] = 1(take nothing, one way);dp[a] += dp[a - c].
1def fewest_coins(coins, amount):2 INF = float("inf")3 dp = [0] + [INF] * amount4 for c in coins:5 for a in range(c, amount + 1): # forwards: the same coin can be used again6 dp[a] = min(dp[a], dp[a - c] + 1)7 return dp[amount] if dp[amount] != INF else -18 9def count_ways(coins, amount): # coins outside: counts combinations10 dp = [1] + [0] * amount11 for c in coins:12 for a in range(c, amount + 1):13 dp[a] += dp[a - c]14 return dp[amount]15 16def count_orders(coins, amount): # amounts outside: counts orderings17 dp = [1] + [0] * amount18 for a in range(1, amount + 1):19 for c in coins:20 if c <= a:21 dp[a] += dp[a - c]22 return dp[amount]23 24print(fewest_coins([1, 3, 4], 6), fewest_coins([1, 3, 4], 10), fewest_coins([2], 3))25print(count_ways([1, 2, 5], 5), count_orders([1, 2, 5], 5))
2 3 -1 4 9
1, 3, 4 makes 6 with at least 2 coins and 10 with at least 3, where greedy gave 3 and 4. The two numbers on the last line differ: 5 can be made by 4 combinations (5; 2 + 2 + 1; 2 + 1 + 1 + 1; five 1s), but if 1 + 2 + 2 and 2 + 1 + 2 count as different, there are 9 orderings. With the coins in the outer loop, each kind of coin is finished before the next starts, so any one group of coins is counted in only one order; with the amounts outside, every amount tries every coin as "the last one", and different orders are counted separately.
| Problem | Times each item can be taken | Inner loop | Transition |
|---|---|---|---|
| 0-1 knapsack | at most once | capacity large to small | max(dp[c], dp[c - w] + v) |
| Unbounded knapsack | any number | capacity small to large | the same |
| Coin change: fewest coins | any number | amount small to large | min(dp[a], dp[a - c] + 1) |
| Coin change: combinations | any number | coins in the outer loop | dp[a] += dp[a - c] |
| Stairs-style: orderings | any number | amounts in the outer loop | dp[a] += dp[a - c] |
In interviews: for a knapsack problem, first say which kind it is: each item at most once (0-1, backwards) or reusable (unbounded, forwards); and what is asked: the most value, the fewest items, whether it can be made, or the number of ways (combinations or orderings). The follow-up you will hear most is "why backwards in one list": the dp[c - w] being read must be from the row above, and going forwards reads a value from this row that may already include the item.
"The fewest coins of 1, 2 and 5 that make 11" and "can the array {1, 5, 11, 5} be split into two halves with equal sums": which knapsack is each?
Making 4 out of 1s and 2s: counted once with the coins in the outer loop, and once with the amounts outside. What does it print?
1def count_ways(coins, amount):2 dp = [1] + [0] * amount3 for c in coins:4 for a in range(c, amount + 1):5 dp[a] += dp[a - c]6 return dp[amount]7 8def count_orders(coins, amount):9 dp = [1] + [0] * amount10 for a in range(1, amount + 1):11 for c in coins:12 if c <= a:13 dp[a] += dp[a - c]14 return dp[amount]15 16print(count_ways([1, 2], 4), count_orders([1, 2], 4))
The fewest coins
✓Complete coin_change(coins, amount): with unlimited coins of each kind, the fewest coins making amount, or -1 if it cannot be made. An unbounded knapsack: the inner loop goes forwards.
3 -1 0 2 4
1def coin_change(coins, amount):2 INF = float("inf")3 dp = [0] + [INF] * amount4 # for each coin c: a from c up to amount, dp[a] becomes the smaller of itself and dp[a - c] + 15 return dp[amount] if dp[amount] != INF else -16 7print(coin_change([1, 2, 5], 11))8print(coin_change([2], 3))9print(coin_change([1], 0), coin_change([1, 3, 4], 6), coin_change([5, 7], 24))
How you write it at work
There is no knapsack in the standard library. The quickest way to a correct version is to write "take it or leave it" directly as a recursion and add @lru_cache: the state (i, cap) is one box of the table, and the cache remembers the table for you.
1from functools import lru_cache2 3items = [(2, 3), (3, 4), (4, 5)]4 5@lru_cache(maxsize=None)6def best(i, cap): # from item i on, with capacity cap, the most value7 if i == len(items):8 return 09 w, v = items[i]10 result = best(i + 1, cap) # leave it11 if w <= cap:12 result = max(result, best(i + 1, cap - w) + v) # take it13 return result14 15print(best(0, 6))16print(best.cache_info())
8 CacheInfo(hits=0, misses=13, maxsize=None, currsize=13)
- Recursion with a cache is the easiest to write and the hardest to get wrong, and it works out only the boxes it actually reaches (13 here, out of a 4 × 7 = 28 box table). But its depth is the number of items n; with thousands of items, fill the table in a loop.
- Arguments must be hashable:
itemsis a list, so it stays outside, and only the indexiand capacitycapare passed. - Mark "cannot be made" with
float("inf")or-1, and remember to turn infinity back into the -1 the problem asks for. - With a huge capacity (10⁹) and few items (n ≤ 40), the table will not fit: go back to backtracking with pruning, or split the items in two halves, list each, and pair them up.
best(i, cap) has @lru_cache, with n items and capacity W. At most how many different entries can end up in the cache?
Summary
Knapsack: take each item or leave it
- dp[i][c] = max(leave it dp[i-1][c], take it dp[i-1][c-w] + v), O(n × W)
- Reading back: different from the box above means taken; subtract its weight
- One list: the 0-1 knapsack runs backwards; forwards it becomes the unbounded knapsack
- Coin change is an unbounded knapsack: min for the fewest coins, += for the ways
- Coins in the outer loop count combinations, amounts in the outer loop count orderings
1dp = [0] * (cap + 1)2for w, v in items:3 for c in range(cap, w - 1, -1):4 dp[c] = max(dp[c], dp[c - w] + v)