Skip to content

Lesson 32 of 40DP families

Knapsack and Subset DP

0/1 and unbounded knapsack, why loop direction and loop order change the answer, and the subset-sum family: partition, target sum, coin change II.

24 min read0/4 questions

A batch scheduler has 64 GB of memory on a node and a queue of jobs, each with a memory cost and a priority. Which set of jobs should run together to get the most priority without going over? A sprint has 30 points of capacity and a backlog of stories with estimates and business value. An ad server has a budget and a list of placements. These are all the same problem: pick items, each with a cost, to make the best total without exceeding a capacity. That is the knapsack problem, and it is the parent of a whole family of interview questions that look unrelated until you see the shape.

The Dynamic Programming lesson solved Coin Change with a 1D table, and the 2D DP lesson filled grids over two prefixes. This lesson goes further: the knapsack table and how to squeeze it into one row, the single most common bug in that squeeze, and why swapping two for loops changes "count combinations" into "count permutations".

0/1 knapsack: the table

Each item has a weight and a value. You may take each item at most once (that is the "0/1": take it or leave it). Maximise value with total weight at most cap.

Greedy by value-per-weight fails here: with capacity 7 and items (weight 5, value 7), (3, 4), (4, 5), the best ratio is the 5-weight item, but then only 2 capacity is left. Taking 3 and 4 gives 9. You need to consider combinations, and DP does that without listing all 2ⁿ of them.

  • State: dp[i][c] = the best value using only the first i items with capacity c.
  • Recurrence: think about the last item, item i. Either you skip it, and the answer is dp[i-1][c], or you take it (if it fits) and the answer is its value plus the best you can do with the earlier items in the capacity that is left: dp[i-1][c - w] + v. Take the larger.
  • Base cases: row 0 (no items) is all 0.
  • Answer: dp[n][cap].

Notice both choices read from row i - 1. That is what "at most once" looks like in the table: after you take item i, you can only combine it with items before it.

0/1 knapsack, weights [1, 3, 4, 5], values [1, 4, 5, 7], capacity 7
01234567
none00000000
w1 v1
w3 v4
w4 v5
w5 v7

Row 0: with no items, every capacity is worth 0. Columns are capacities 0 to 7.

1/6
Python
def knapsack_table(weights, values, cap): n = len(weights) # dp[i][c] = best value using only the first i items with capacity c dp = [[0] * (cap + 1) for _ in range(n + 1)] for i in range(1, n + 1): w, v = weights[i - 1], values[i - 1] for c in range(cap + 1): dp[i][c] = dp[i - 1][c] # skip item i if w <= c: dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v) # take it # walk back to find which items were taken taken, c = [], cap for i in range(n, 0, -1): if dp[i][c] != dp[i - 1][c]: # value changed, so item i was taken taken.append(i - 1) c -= weights[i - 1] return dp[n][cap], taken[::-1] best, items = knapsack_table([1, 3, 4, 5], [1, 4, 5, 7], 7)assert (best, items) == (9, [1, 2])assert knapsack_table([5], [10], 4) == (0, [])assert knapsack_table([], [], 10) == (0, [])print(best, items)
Output
Press Run (⌘ Enter) to see what happens.

Time and space are both O(n × cap). When an interviewer only wants the number, the next step is to cut the space.

One row, and why it runs backwards

Each row reads only the row above it. As with the rolling rows in 2D DP, you could keep two rows. You can go further and keep one, updating it in place, but only if you get the direction right.

The update is dp[c] = max(dp[c], dp[c - w] + v). On the right-hand side, dp[c] must mean "previous row" and so must dp[c - w]. If you loop c upward, by the time you reach c you have already overwritten dp[c - w] with this item's row. Reading it means "take this item on top of a total that already includes this item". The item gets used again and again.

Loop c downward and dp[c - w] is always still untouched from the previous row, because smaller indices are updated later.

One item: weight 2, value 3. Capacity 6.
0
0
0
1
0
2
0
3
0
4
0
5
0
6

One row of capacities 0 to 6, all 0. There is exactly one item, so the right answer for every capacity of 2 or more is 3.

1/6

That forward "bug" is exactly right for a different problem. In unbounded knapsack every item can be taken any number of times, and the forward loop is the correct algorithm: reading this pass's value means "take another copy".

Python
def knapsack_01(weights, values, cap): dp = [0] * (cap + 1) for w, v in zip(weights, values): for c in range(cap, w - 1, -1): # BACKWARDS: each item once dp[c] = max(dp[c], dp[c - w] + v) return dp[cap] def knapsack_unbounded(weights, values, cap): dp = [0] * (cap + 1) for w, v in zip(weights, values): for c in range(w, cap + 1): # FORWARDS: reuse allowed dp[c] = max(dp[c], dp[c - w] + v) return dp[cap] assert knapsack_01([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9assert knapsack_01([2], [3], 6) == 3 # one item, used onceassert knapsack_unbounded([2], [3], 6) == 9 # same item, used three timesassert knapsack_unbounded([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9print(knapsack_01([2], [3], 6), knapsack_unbounded([2], [3], 6))
Output
Press Run (⌘ Enter) to see what happens.

The 1D form costs you the ability to walk back and list the chosen items, the same trade-off as rolling rows in 2D DP. Keep the full table when you need the items, not just the value.

Predict the outputPython

This was meant to be 0/1 knapsack with one item (weight 2, value 3) and capacity 6. What does it print?

dp = [0] * 7
w, v = 2, 3
for c in range(w, 7):
  dp[c] = max(dp[c], dp[c - w] + v)
print(dp)
Need a nudge? Hints walk you through it.

Coins: the unbounded family

Coins are the classic unbounded items: you can use each denomination any number of times. Three questions use the same forward loop and differ only in what the cell holds.

  • Coin Change (fewest coins): cell is a minimum, dp[0] = 0, everything else infinity, combine with min(dp[a], dp[a - coin] + 1). You saw it with amounts on the outside in the Dynamic Programming lesson; for a minimum, either loop order gives the same answer.
  • Coin Change II (number of ways): cell is a count, dp[0] = 1 (one way to make zero: use nothing), combine with +=.
  • Combination Sum IV (number of ordered sequences): the same += with the loops swapped.

That last line is the most tested idea in this lesson.

Loop order: combinations versus permutations

With coins [1, 2] and amount 4, how many ways are there? It depends on whether 1 + 1 + 2 and 2 + 1 + 1 are the same way. As multisets there are 3: {1,1,1,1}, {1,1,2}, {2,2}. As ordered sequences there are 5: 1111, 112, 121, 211, 22.

Coins on the outside gives combinations. Each pass adds one denomination to the set you may use. When you process coin 2, every way already in the table uses only coin 1. So every way you build has all its 1s "before" its 2s: each multiset is built in exactly one order, sorted by coin, and counted once.

Amounts on the outside gives permutations. For each amount a you ask "what was the last coin?" and try every coin. dp[3] gets the ways ending in 1 plus the ways ending in 2, so 1 + 2 and 2 + 1 land in different buckets and both count.

coins [1, 2], amounts 0 to 4: same recurrence, loops swapped
01234
coins outer1
amount outer1

Both start with dp[0] = 1: one way to make 0, by choosing nothing.

1/6
Python
from itertools import product def combinations(coins, amount): # Coin Change II dp = [1] + [0] * amount for coin in coins: # coins OUTSIDE for a in range(coin, amount + 1): dp[a] += dp[a - coin] return dp[amount] def permutations(coins, amount): # Combination Sum IV dp = [1] + [0] * amount for a in range(1, amount + 1): # amounts OUTSIDE for coin in coins: if coin <= a: dp[a] += dp[a - coin] return dp[amount] def min_coins(coins, amount): # Coin Change: same shape, min instead of + INF = float("inf") dp = [0] + [INF] * amount for coin in coins: for a in range(coin, amount + 1): dp[a] = min(dp[a], dp[a - coin] + 1) return dp[amount] if dp[amount] != INF else -1 # brute force check: every ordered sequence of coins that sums to the amountdef brute(coins, amount): seqs = [s for k in range(amount + 1) for s in product(coins, repeat=k) if sum(s) == amount] return len({tuple(sorted(s)) for s in seqs}), len(seqs) for coins, amount in [([1, 2], 4), ([1, 2, 5], 5), ([2, 3], 7), ([3], 2)]: assert (combinations(coins, amount), permutations(coins, amount)) == brute(coins, amount) assert min_coins([1, 2, 5], 11) == 3 and min_coins([2], 3) == -1print(combinations([1, 2], 4), permutations([1, 2], 4))
Output
Press Run (⌘ Enter) to see what happens.

The brute-force check is worth copying as a habit. For counting problems, a tiny exhaustive search over small inputs catches the swapped-loop bug in seconds, and the bug otherwise produces plausible numbers that are just a bit too big.

Quick check
You need the number of distinct ways to pay 10 using unlimited coins of 1, 2 and 5, where 5+2+2+1 and 2+5+1+2 are the same way. Which loop structure is correct?
Need a nudge? A hint rules out a wrong answer.

Subset sum: true or false instead of a value

Drop the values and ask only "can some subset of these numbers hit exactly this sum?". The cell becomes a boolean, and the 0/1 backward loop is unchanged. Three well-known problems are this in disguise.

Partition Equal Subset Sum. Can the array be split into two parts with equal sums? Both parts would equal total / 2, so the question is "does some subset sum to total / 2?". If the total is odd, the answer is no before any DP. Stop early as soon as dp[target] becomes true.

Partition [1, 5, 11, 5]: target 11. Cell s is 1 when some subset sums to s.
1
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
0
10
0
11

Total 22, so target 11. Only sum 0 is reachable at the start (the empty subset).

1/4

Because each new row is "old set OR old set shifted by x", Python's arbitrary-size integers give a neat shortcut: hold the whole row as the bits of one integer and do bits |= bits << x. Each item costs one shift and one OR over target bits, which runs in fast C code and is usually many times faster than the Python loop. It is the same O(n × target) work, just in machine words.

Python
def can_partition(nums): total = sum(nums) if total % 2: # odd total can never split evenly return False target = total // 2 dp = [True] + [False] * target # dp[s]: some subset sums to s for x in nums: for s in range(target, x - 1, -1): dp[s] = dp[s] or dp[s - x] if dp[target]: return True # early exit return dp[target] def can_partition_bits(nums): total = sum(nums) if total % 2: return False bits = 1 # bit s is set when sum s is reachable for x in nums: bits |= bits << x # every old sum, plus x return (bits >> (total // 2)) & 1 == 1 cases = [([1, 5, 11, 5], True), ([1, 2, 3, 5], False), ([2, 2], True), ([1], False), ([3, 3, 3, 4, 5], True), ([100, 100, 99, 1], False)]for nums, want in cases: assert can_partition(nums) == want == can_partition_bits(nums), numsprint(can_partition([1, 5, 11, 5]), can_partition([1, 2, 3, 5]))
Output
Press Run (⌘ Enter) to see what happens.

Target Sum. Put + or - in front of every number so the expression equals target; count the ways. Call the plus group's sum P and the minus group's sum N. Then P - N = target and P + N = total. Add them: P = (total + target) / 2. So the question becomes "how many subsets sum to P?", a counting subset sum. Two guards first: if abs(target) > total nothing works, and if total + target is odd, P is not an integer, so the answer is 0. Zeros need no special case: the backward loop runs down to s = 0 for a zero, doubling every count, which matches "+0 and -0 are different choices".

Last Stone Weight II. Smashing stones until one is left turns out to be the same as splitting them into two piles and subtracting. To make the difference smallest, find the largest reachable subset sum not above total / 2; the answer is total - 2 × best.

Python
def target_sum(nums, target): # P - N = target and P + N = total, so P = (total + target) / 2 total = sum(nums) if abs(target) > total or (total + target) % 2: return 0 p = (total + target) // 2 dp = [1] + [0] * p # dp[s]: number of subsets summing to s for x in nums: for s in range(p, x - 1, -1): # 0/1: backwards dp[s] += dp[s - x] return dp[p] def last_stone_weight_ii(stones): # split into two piles as evenly as possible; answer = total - 2 * best total = sum(stones) half = total // 2 reach = [True] + [False] * half for x in stones: for s in range(half, x - 1, -1): reach[s] = reach[s] or reach[s - x] best = max(s for s in range(half + 1) if reach[s]) return total - 2 * best assert target_sum([1, 1, 1, 1, 1], 3) == 5assert target_sum([1], 2) == 0 # |target| > totalassert target_sum([1, 2], 2) == 0 # parity: 3 + 2 is oddassert target_sum([0, 0, 1], 1) == 4 # each zero can be +0 or -0assert last_stone_weight_ii([2, 7, 4, 1, 8, 1]) == 1assert last_stone_weight_ii([31, 26, 33, 21, 40]) == 5print(target_sum([1, 1, 1, 1, 1], 3), last_stone_weight_ii([2, 7, 4, 1, 8, 1]))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Target Sum with nums = [2, 3, 4] and target = 2. What subset sum P do you count, and what is the answer?
Need a nudge? A hint rules out a wrong answer.

Two capacities at once

Ones and Zeroes gives you binary strings and two budgets: at most m zeros and n ones in total. Pick as many strings as possible. Each string is an item with a two-part weight, so the state needs both capacities: dp[z][o] = the most strings using at most z zeros and o ones. Still 0/1, so both capacity loops run backwards. The cost is O(strings × m × n).

Python
def find_max_form(strs, m, n): # dp[z][o] = most strings using at most z zeros and o ones dp = [[0] * (n + 1) for _ in range(m + 1)] for s in strs: zeros, ones = s.count("0"), s.count("1") for z in range(m, zeros - 1, -1): # both capacities backwards for o in range(n, ones - 1, -1): dp[z][o] = max(dp[z][o], dp[z - zeros][o - ones] + 1) return dp[m][n] assert find_max_form(["10", "0001", "111001", "1", "0"], 5, 3) == 4assert find_max_form(["10", "0", "1"], 1, 1) == 2print(find_max_form(["10", "0001", "111001", "1", "0"], 5, 3))
Output
Press Run (⌘ Enter) to see what happens.

The same pattern covers real constraints with two resources: CPU and memory per job, or budget and headcount per project. Each extra capacity multiplies the table, so three or more usually means the DP is too big and you need a heuristic or a solver.

Match the pairs0/5 matched

Match each problem to the knapsack variant and loop it needs.

Choose an item, then its match on the other side.

Pseudo-polynomial: why the constraints matter

Knapsack DP runs in O(n × W), where W is the capacity. That looks polynomial, but W is a number, not a count of things. Writing W takes only about log₂ W bits, so doubling the length of the input can square W. That is called pseudo-polynomial time, and 0/1 knapsack is NP-hard in general: no known algorithm is polynomial in the input's bit length.

In practice, read the constraints:

  • n up to a few hundred and capacity or sum up to around 10⁴ to 10⁵: the table is a few million cells. DP is the intended answer.
  • Capacity up to 10⁹ but values small: flip the state. Let dp[v] be the minimum weight that achieves value v, and find the largest v with dp[v] ≤ W. The table size now depends on the total value.
  • Capacity huge and n up to about 40: meet in the middle. Split the items in half, list all 2²⁰ subset sums of each half, sort one list, and binary search for the best partner of each sum in the other.
  • Floating-point weights: there is no index to put them in. Scale to integers if the precision is known, or use a different method.

At work, a real knapsack-shaped problem with thousands of items and big capacities is usually handed to an integer programming solver, or solved with a good-enough greedy plus a bound on how far from optimal it can be. Knowing when the exact DP stops fitting is the senior part.

Key terms
0/1 knapsack
Each item is taken at most once. In one row, loop the capacity backwards.
unbounded knapsack
Items can be reused. In one row, loop the capacity forwards.
subset sum
Can some subset hit an exact total? A boolean 0/1 knapsack with weights equal to values.
combinations vs permutations
Items in the outer loop count each multiset once; amounts in the outer loop count every ordering.
pseudo-polynomial
Polynomial in the numeric value of the input (like capacity W), not in its bit length. O(n × W) is fine only when W is small.
meet in the middle
Split n items into two halves, enumerate each half's 2^(n/2) sums, and combine with sorting and binary search.