Dynamic Programming · Pattern 7 of 12

Knapsack: choose items under a capacity

dp[c] = the best value (or number of ways) using capacity c. Loop capacity right to left when each item may be used once (0/1), and left to right when items can be reused (unbounded).

4 variations · 11 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Choose a subset of items with a weight or cost limit
  • Make an amount from coins, or split numbers into two groups with given sums
  • Each item is used at most once, or as many times as you like

The template

Knapsack
// 0/1 knapsack: each item at most once, so capacity goes right to left
int knapsack(int W, int[] val, int[] wt) {
    int[] dp = new int[W + 1];             // dp[c] = best value with capacity c
    for (int i = 0; i < wt.length; i++)
        for (int c = W; c >= wt[i]; c--)   // dp[c - wt[i]] still means "without item i"
            dp[c] = Math.max(dp[c], dp[c - wt[i]] + val[i]);
    return dp[W];
}

// Coin Change: fewest coins (unbounded, left to right)
int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);           // "infinity": more coins than could ever be needed
    dp[0] = 0;
    for (int c = 1; c <= amount; c++)
        for (int coin : coins)
            if (coin <= c) dp[c] = Math.min(dp[c], dp[c - coin] + 1);
    return dp[amount] > amount ? -1 : dp[amount];
}

// Coin Change II: number of combinations (coins in the outer loop, so order does not matter)
int change(int amount, int[] coins) {
    int[] dp = new int[amount + 1];
    dp[0] = 1;                             // one way to make 0: take nothing
    for (int coin : coins)
        for (int c = coin; c <= amount; c++)
            dp[c] += dp[c - coin];
    return dp[amount];
}

The variations

  1. 10/1 knapsack: each item once

    For each item, go over capacities from high to low: dp[c] = max(dp[c], dp[c - w] + v). Many problems hide a knapsack: Partition Equal Subset Sum asks whether sum / 2 is reachable, Target Sum turns +/- signs into one subset with a fixed sum, Painting the Walls uses "walls covered" as the capacity, and House of Cards picks distinct row sizes.

  2. 2Unbounded knapsack: reuse items

    The same loop with capacity from low to high. Now dp[c - w] may already include this item, which is exactly what "unlimited copies" means.

    Now you solve
  3. 3Coins: fewest coins, or number of ways

    Fewest coins: dp[c] = min(dp[c - coin] + 1), starting from infinity with dp[0] = 0. Number of ways: dp[c] += dp[c - coin] with dp[0] = 1, and coins in the outer loop so each combination is counted once.

    Now you solve
  4. 4Fractional knapsack: greedy, not DP

    When you may take part of an item, sort by value per unit of weight and take the best ones first, splitting the last. It is the contrast case: greedy is correct here only because items can be cut.

Mistakes to avoid

  • 0/1 knapsack with capacity going left to right: an item gets added twice in the same pass.
  • Coin Change II with the amount loop outside and coins inside: that counts orderings (1 + 2 and 2 + 1) as different.
  • Using greedy on 0/1 knapsack or coin change: biggest-first fails, for example coins [1, 3, 4] and amount 6.
Next: String DP: two indexes, one per string →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.