Knapsack DP
The 0/1 and unbounded knapsack patterns — subset sum, partition, target sum, coin change — and the loop direction that separates them.
A whole family of DP problems is really knapsack: choose items, each with a "weight", to hit or stay under a capacity while optimising something (or counting the ways). Recognise the family and the code is almost always the same 1-D table. (DP foundations: Dynamic programming.)
- "Can a subset sum to T?", "partition into two equal-sum halves", "assign + / − signs to reach a target".
- "Minimum number of coins/items to make an amount", "number of ways to make an amount".
- Any choice per item of take or skip (0/1) or take any number (unbounded) under a budget.
The state
dp[c] = the best value (or true/false, or a count) achievable with capacity c using the items processed so far. For each item with weight w and value v:
The one rule to remember
Loop capacity downwards, from C to w. dp[c − w] still holds the value from before this item, so the item is counted at most once.
Loop capacity upwards, from w to C. dp[c − w] may already include this item, so the item can be taken again.
// 0/1 knapsack: max value within capacity C
int knapsack01(int[] w, int[] v, int C) {
int[] dp = new int[C + 1];
for (int i = 0; i < w.length; i++)
for (int c = C; c >= w[i]; c--) // downwards!
dp[c] = Math.max(dp[c], dp[c - w[i]] + v[i]);
return dp[C];
}
// Partition equal subset sum (0/1, boolean)
boolean canPartition(int[] nums) {
int sum = Arrays.stream(nums).sum();
if (sum % 2 == 1) return false;
boolean[] dp = new boolean[sum / 2 + 1];
dp[0] = true;
for (int x : nums)
for (int c = sum / 2; c >= x; c--) dp[c] |= dp[c - x];
return dp[sum / 2];
}
// Coin change: fewest coins (unbounded, min)
int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1); // "infinity"
dp[0] = 0;
for (int coin : coins)
for (int c = coin; c <= amount; c++) // upwards!
dp[c] = Math.min(dp[c], dp[c - coin] + 1);
return dp[amount] > amount ? -1 : dp[amount];
}def knapsack01(w, v, C):
dp = [0] * (C + 1)
for wi, vi in zip(w, v):
for c in range(C, wi - 1, -1): # downwards!
dp[c] = max(dp[c], dp[c - wi] + vi)
return dp[C]
def can_partition(nums):
s = sum(nums)
if s % 2:
return False
dp = [True] + [False] * (s // 2)
for x in nums:
for c in range(s // 2, x - 1, -1):
dp[c] = dp[c] or dp[c - x]
return dp[s // 2]
def coin_change(coins, amount):
INF = amount + 1
dp = [0] + [INF] * amount
for coin in coins:
for c in range(coin, amount + 1): # upwards!
dp[c] = min(dp[c], dp[c - coin] + 1)
return -1 if dp[amount] == INF else dp[amount]function knapsack01(w: number[], v: number[], C: number): number {
const dp = new Array(C + 1).fill(0);
for (let i = 0; i < w.length; i++)
for (let c = C; c >= w[i]; c--) dp[c] = Math.max(dp[c], dp[c - w[i]] + v[i]);
return dp[C];
}
function coinChange(coins: number[], amount: number): number {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (const coin of coins)
for (let c = coin; c <= amount; c++) dp[c] = Math.min(dp[c], dp[c - coin] + 1);
return dp[amount] === Infinity ? -1 : dp[amount];
}Counting: combinations vs permutations
For "number of ways to make the amount" the recurrence becomes dp[c] += dp[c − coin], and the loop order decides what you count:
| Outer loop | Inner loop | Counts | Problem |
|---|---|---|---|
| coins | amounts | combinations (1+2 is the same as 2+1) | Coin Change II |
| amounts | coins | permutations (order matters) | Combination Sum IV |
Problems that are secretly knapsack
| Problem | Translation |
|---|---|
| Target Sum (± signs) | Subset with sum (total + target) / 2; count the ways |
| Last Stone Weight II | Split into two piles with minimal difference: subset sum closest to total / 2 |
| Ones and Zeroes | 0/1 knapsack with two capacities (zeros, ones): 2-D dp |
| Perfect Squares | Unbounded: fewest squares summing to n |
| Word Break | Unbounded over words; "can I fill the prefix?" |
| Profitable Schemes | 0/1 with capacity members and a profit dimension |
- Partition Equal Subset Summedium
- Target Sumreduce to subset countmedium
- Last Stone Weight IImedium
- Coin Changemedium
- Coin Change IIcoins outer loopmedium
- Combination Sum IVamount outer loopmedium
- Perfect Squaresmedium
- Ones and Zeroestwo capacitiesmedium
- Word Breakmedium
- Profitable Schemeshard
- Take/skip under a budget ⇒ knapsack; 1-D
dp[capacity]. - 0/1: capacity loop goes down. Unbounded: it goes up.
- Counting: coins outer = combinations; amount outer = permutations.
- Many problems reduce to subset sum after a little algebra.
- O(n · C) is pseudo-polynomial.