Knapsack DP

The 0/1 and unbounded knapsack patterns — subset sum, partition, target sum, coin change — and the loop direction that separates them.

Advanced 3 min readLesson 23 of 25

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.)

When to use this pattern
  • "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:

dp[c]=max⁡(dp[c], dp[c−w]+v)dp[c] = \max\big(dp[c],\ dp[c - w] + v\big)
012345–ABC000000000333004447004559
Items A (w3, v3), B (w2, v4), C (w3, v5); capacity 5. Best = 9 (B + C).

The one rule to remember

0/1 (each item once)

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.

Unbounded (reuse items)

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];
}

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 loopInner loopCountsProblem
coinsamountscombinations (1+2 is the same as 2+1)Coin Change II
amountscoinspermutations (order matters)Combination Sum IV

Problems that are secretly knapsack

ProblemTranslation
Target Sum (± signs)Subset with sum (total + target) / 2; count the ways
Last Stone Weight IISplit into two piles with minimal difference: subset sum closest to total / 2
Ones and Zeroes0/1 knapsack with two capacities (zeros, ones): 2-D dp
Perfect SquaresUnbounded: fewest squares summing to n
Word BreakUnbounded over words; "can I fill the prefix?"
Profitable Schemes0/1 with capacity members and a profit dimension
TimeO(n · C)SpaceO(C)
Practice problems
  • 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
Key takeaways
  • 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.