The knapsack problem asks which items to pack into a bag of limited capacity to maximize total value. It is the template behind a whole family of interview favorites: subset sum, partition equal subset sum, target sum and both coin change problems. Master one table, dp[i][w], and one subtle detail, which direction to loop over capacity, and the entire family falls into place.
Think of it like
Packing a carry-on bag
Your airline allows 7 kg of hand luggage. Each thing you could bring has a weight and a "happiness" value. In 0/1 knapsack you own one of each item, so each is in or out. In unbounded knapsack you are buying from a shop with unlimited stock (like coins of each denomination). In bounded knapsack the shop has only a few of each. The question is always the same: given the space left, is this item worth it?
The knapsack family
| Variant | Copies of each item | 1D capacity loop | Classic problems |
|---|---|---|---|
| 0/1 knapsack | At most 1 | Backward (W down to wᵢ) | Subset sum, partition equal subset sum, target sum |
| Unbounded knapsack | Unlimited | Forward (wᵢ up to W) | Coin change, coin change II, rod cutting, perfect squares |
| Bounded knapsack | At most cᵢ | Binary-split into 0/1 items, then backward | Limited coins, limited stock |
| Fractional knapsack | Any fraction | Not DP: greedy by value/weight | Loading divisible goods |
0/1 knapsack: the 2D table
You have n items, item i with weight wᵢ and value vᵢ, and a capacity W. Each item can be taken once or not at all. Brute force tries all 2ⁿ subsets. DP notices that after deciding the first i items, the only thing that matters for the rest is how much capacity is left.
- 1
State
dp[i][w]= the maximum value achievable using only the firstiitems with a capacity limit ofw. - 2
Last decision
Item
i(1-based) is either left out, givingdp[i-1][w], or packed, which requireswᵢ ≤ wand givesdp[i-1][w - wᵢ] + vᵢ. Take the max. - 3
Base cases
dp[0][w] = 0for everyw: with no items, the value is zero. Columnw = 0is also all zeros. - 4
Order and answer
Rows by increasing
i; within a row, any order works because rowionly reads rowi-1. The answer isdp[n][W].
Worked example with capacity W = 7 and four items: A (1 kg, $1), B (3 kg, $4), C (4 kg, $5), D (5 kg, $7). The visualization above fills this kind of table cell by cell: each cell looks straight up (leave) and up-left by the item's weight (take).
| items \ w | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| + A (1 kg, $1) | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| + B (3 kg, $4) | 0 | 1 | 1 | 4 | 5 | 5 | 5 | 5 |
| + C (4 kg, $5) | 0 | 1 | 1 | 4 | 5 | 6 | 6 | 9 |
| + D (5 kg, $7) | 0 | 1 | 1 | 4 | 5 | 7 | 8 | 9 |
Reconstructing the items. Start at (n, W). If dp[i][w] ≠ dp[i-1][w], item i was taken: record it and move to (i-1, w - wᵢ). Otherwise move to (i-1, w). Here dp[4][7] = dp[3][7], so D is not taken; dp[3][7] ≠ dp[2][7], so C is taken and we jump to w = 3; dp[2][3] ≠ dp[1][3], so B is taken. The answer is {B, C} for $9.
One row is enough: why iterate backward
Row i reads only row i-1, and only at the same or smaller capacity. So we can keep a single array dp[w] and overwrite it in place, as long as each read still sees the old (row i-1) value.
Going from high w to low w, the cell dp[w - wᵢ] lies to the left and has not been touched yet in this round, so it still holds the row i-1 value. Going forward instead, dp[w - wᵢ] would already include item i, and the item would be packed a second time. Watch it happen with one item (2 kg, $3) and capacity 4:
| Loop direction | Update order | dp after the item | Meaning |
|---|---|---|---|
| Backward (correct for 0/1) | dp[4] = 0 + 3, then dp[3], then dp[2] = 0 + 3 | [0, 0, 3, 3, 3] | Best value is $3: the item once |
| Forward (wrong for 0/1) | dp[2] = 0 + 3, then dp[3], then dp[4] = dp[2] + 3 = 6 | [0, 0, 3, 3, 6] | Value $6: the item was packed twice |
Unbounded knapsack
With unlimited copies, taking item i leaves you in the same row (you may take it again), not the previous one. In 1D that means iterating capacity forward so that dp[w - wᵢ] already reflects item i.
Rod cutting is the classic example: a rod of length n can be cut into pieces, a piece of length k sells for price[k], and you want the maximum revenue. Each piece length is an item with unlimited copies, and the rod length is the capacity.
Bounded knapsack and binary splitting
Now item i has cᵢ copies. The naive approach expands it into cᵢ separate 0/1 items, costing O(W·Σcᵢ). Binary splitting does much better: bundle the copies into groups of 1, 2, 4, …, 2ᵏ⁻¹ and a remainder r = cᵢ − (2ᵏ − 1). Every count from 0 to cᵢ can be formed by choosing a subset of these bundles, so 0/1 knapsack over the bundles is equivalent, with only O(log cᵢ) items per original item.
| Copies wanted (c = 13) | Bundles used (1, 2, 4, 6) |
|---|---|
| 5 | 1 + 4 |
| 7 | 1 + 2 + 4 |
| 9 | 1 + 2 + 6 |
| 11 | 1 + 4 + 6 |
| 12 | 2 + 4 + 6 |
| 13 | 1 + 2 + 4 + 6 |
def bounded_knapsack(weights, values, counts, W):
dp = [0] * (W + 1)
for w, v, c in zip(weights, values, counts):
k = 1
while c > 0:
take = min(k, c) # bundle of 'take' copies
bw, bv = take * w, take * v
for cap in range(W, bw - 1, -1): # 0/1 step: backward
dp[cap] = max(dp[cap], dp[cap - bw] + bv)
c -= take
k *= 2
return dp[W]Subset sum
Given numbers and a target T, can some subset sum to exactly T? This is 0/1 knapsack where weight = value = the number, and the aggregate is logical OR instead of max.
- 1
State
can[s]= true if some subset of the numbers processed so far sums to exactlys. - 2
Transition
For each number
x, a sumsbecomes reachable if it already was, or ifs - xwas reachable beforexwas considered. - 3
Base case
can[0] = true: the empty subset sums to zero. - 4
Order
Each number once, with
srunning backward fromTtoxsoxis not reused.
| after number | s=0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| (start) | T | F | F | F | F | F | F | F | F |
| 2 | T | F | T | F | F | F | F | F | F |
| 3 | T | F | T | T | F | T | F | F | F |
| 5 | T | F | T | T | F | T | F | T | T |
Partition equal subset sum
Can the array be split into two parts with equal sums? Both parts must sum to total / 2, so the question is simply subset sum with T = total / 2. If the total is odd, the answer is immediately false.
[1, 5, 11, 5]: total 22, target 11. The subset {11} (or {1, 5, 5}) works, so true.[1, 2, 3, 5]: total 11 is odd, so false without any DP.- Time O(n·total), space O(total). Early exit as soon as
can[T]becomes true.
def can_partition(nums: list[int]) -> bool:
total = sum(nums)
if total % 2:
return False
target = total // 2
can = [False] * (target + 1)
can[0] = True
for x in nums:
for s in range(target, x - 1, -1): # backward: each number once
can[s] = can[s] or can[s - x]
if can[target]:
return True
return can[target]Target sum
Put a + or - in front of every number so that the expression equals target; count the ways. It looks like a search over 2ⁿ sign patterns, but a little algebra turns it into counting subsets.
- If
total + targetis odd, or|target| > total, the answer is 0. - Otherwise count subsets with sum
Pusing 0/1 knapsack counting:ways[s] += ways[s − x], backward, withways[0] = 1. - Zeros are handled naturally: each zero doubles the count, because +0 and −0 are different sign choices.
nums = [1, 1, 1, 1, 1],target = 3:P = (5 + 3) / 2 = 4, and there are C(5, 4) = 5 ways to choose which four ones are positive.
def find_target_sum_ways(nums: list[int], target: int) -> int:
total = sum(nums)
if abs(target) > total or (total + target) % 2:
return 0
P = (total + target) // 2
ways = [0] * (P + 1)
ways[0] = 1 # the empty subset
for x in nums:
for s in range(P, x - 1, -1): # backward: each number once
ways[s] += ways[s - x]
return ways[P]Coin change: fewest coins
Given coin denominations (unlimited supply) and an amount, find the minimum number of coins that make the amount, or -1 if impossible. Each coin is an unbounded item with weight = its value and cost = 1 coin, and we minimize instead of maximize.
- 1
State
dp[a]= the fewest coins that sum to exactlya, or ∞ ifacannot be made. - 2
Last decision
The last coin added was some
c ≤ a; before it, we had madea - coptimally. - 3
Base case
dp[0] = 0; every other amount starts at ∞. - 4
Order and answer
Increasing
a(or coins outer, amounts forward: both work for min). The answer isdp[amount], mapped to -1 if still ∞.
| amount a | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| dp[a] | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
| best last coin | 1 | 1 | 3 | 4 | 1 (or 4) | 3 |
c is tried as the last coin by reading dp[a − c], and last[a] records the winner so the coins can be rebuilt. The side panel compares the answer with greedy; try the "Greedy stuck" preset, where largest-first never reaches the amount at all.Coin change II: counting combinations
Now count how many combinations of coins make the amount: {1, 2} and {2, 1} are the same combination. The recurrence is a sum instead of a min, and the loop order is the entire difficulty.
| after coin | a=0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| (start) | 1 | 0 | 0 | 0 | 0 | 0 |
| 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 | 2 | 3 | 3 |
| 5 | 1 | 1 | 2 | 2 | 3 | 4 |
ways array after one more coin joins. A cell reads the row above (combinations without the new coin) and its own row c to the left (combinations that already end in c, which is what lets a coin repeat). Switch to Permutations to run the same update with the loops swapped and watch the count grow to 9.Coins outer, amount inner: combinations
- Each row adds one denomination to the toolbox
- Coins are always used in the order of the coin list, so every multiset is built in exactly one way
- coins [1, 2], amount 3 → 2 ({1,1,1}, {1,2})
- LeetCode 518: Coin Change II
Amount outer, coins inner: permutations
- For each amount, the last coin can be any denomination
- Different orders end with different last coins, so they are counted separately
- coins [1, 2], amount 3 → 3 (1+1+1, 1+2, 2+1)
- LeetCode 377: Combination Sum IV (and climbing stairs with step sizes)
Spotting a knapsack in disguise
| Problem | Items | Capacity | Copies | Aggregate |
|---|---|---|---|---|
| 0/1 knapsack | items (w, v) | weight limit | 1 | max value |
| Subset sum / partition | numbers | target sum | 1 | OR (reachable?) |
| Target sum | numbers | P = (total + target)/2 | 1 | count (+) |
| Last stone weight II | stones | total / 2 | 1 | OR, then closest sum |
| Ones and zeroes | strings | two capacities (m zeros, n ones) | 1 | max count |
| Coin change | coins | amount | ∞ | min count |
| Coin change II | coins | amount | ∞ | count combinations |
| Perfect squares | squares 1, 4, 9, … | n | ∞ | min count |
Complexity
| Problem / version | Time | Space | Notes |
|---|---|---|---|
| 0/1 knapsack, 2D table | O(n·W) | O(n·W) | Keeps the table, so items can be reconstructed |
| 0/1 knapsack, 1D | O(n·W) | O(W) | Capacity loop runs backward |
| Unbounded knapsack, 1D | O(n·W) | O(W) | Capacity loop runs forward |
| Bounded, naive expansion | O(W·Σcᵢ) | O(W) | One 0/1 item per copy |
| Bounded, binary splitting | O(W·Σ log cᵢ) | O(W) | O(n·W) with a monotonic queue |
| Subset sum / partition | O(n·T) | O(T) | O(n·T / 64) with a bitset |
| Coin change / coin change II | O(k·A) | O(A) | k coins, amount A |
All of these are pseudo-polynomial: polynomial in the numeric capacity, exponential in its bit length. Knapsack itself is NP-complete.
Implementation
The full (n+1) × (W+1) table, then a backward walk that recovers which items were packed.
def knapsack_01(weights: list[int], values: list[int], W: int) -> tuple[int, list[int]]:
n = len(weights)
# dp[i][w] = best value using the first i items with capacity w
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
wi, vi = weights[i - 1], values[i - 1]
for w in range(W + 1):
dp[i][w] = dp[i - 1][w] # leave item i
if wi <= w:
dp[i][w] = max(dp[i][w], dp[i - 1][w - wi] + vi) # take it
# Walk back: a changed value means item i was taken.
chosen, w = [], W
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][W], chosen[::-1]
print(knapsack_01([1, 3, 4, 5], [1, 4, 5, 7], 7)) # (9, [1, 2])Key takeaways
- 0/1 knapsack:
dp[i][w] = max(dp[i-1][w], dp[i-1][w - wᵢ] + vᵢ), O(n·W) time, reducible to O(W) space. - In 1D, iterate capacity backward for 0/1 (each item once) and forward for unbounded (items reusable).
- Bounded knapsack becomes 0/1 knapsack over O(log cᵢ) binary bundles per item.
- Subset sum, partition and target sum are 0/1 knapsacks with OR or counting instead of max; coin change problems are unbounded knapsacks.
- For counting, coins in the outer loop count combinations; amounts in the outer loop count permutations.
Common pitfalls
- Iterating capacity forward in a 0/1 problem, which silently lets items be used more than once.
- Initializing a min-DP with 0 instead of ∞ (or
amount + 1), so impossible amounts look free. - Using
Integer.MAX_VALUEas infinity and then adding 1 to it, which overflows to a negative number. - Swapping the loops in coin change II and returning the number of ordered sequences instead of combinations.
- Forgetting the parity and range checks in target sum or partition (odd totals, |target| > total).
Interview tips
- Classify first: "capacity is the target sum, each number is used once, I am counting": that tells you the table, loop direction and aggregate in one sentence.
- Write the 2D version if you are unsure, then compress to 1D and explain the loop direction.
- Mention that O(n·W) is pseudo-polynomial and knapsack is NP-complete; it shows depth and explains why constraints on W matter.
- For coin change, give the greedy counterexample (
[1, 3, 4], amount 6) to justify DP.
Real-world applications
- Capital budgeting: choosing projects with costs and expected returns under a fixed budget.
- Cargo and container loading, cutting stock and rod cutting in manufacturing.
- Making change in vending machines and payment systems with non-standard denominations.
- Selecting ads or features under latency, memory or token budgets.
- Cryptography: early public-key systems (Merkle-Hellman) were built on subset sum hardness.
Practice problems
Test yourself
In the 1D 0/1 knapsack, why must the capacity loop run from W down to wᵢ?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.