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).
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
// 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];
} def knapsack(W, val, wt):
dp = [0] * (W + 1) # dp[c] = best value with capacity c
for v, w in zip(val, wt):
for c in range(W, w - 1, -1): # right to left: each item at most once
dp[c] = max(dp[c], dp[c - w] + v)
return dp[W]
def coin_change(coins, amount):
INF = amount + 1 # more coins than could ever be needed
dp = [0] + [INF] * amount
for c in range(1, amount + 1):
for coin in coins:
if coin <= c:
dp[c] = min(dp[c], dp[c - coin] + 1)
return -1 if dp[amount] > amount else dp[amount]
def change(amount, coins):
dp = [1] + [0] * amount # one way to make 0: take nothing
for coin in coins: # coins outside: each combination counted once
for c in range(coin, amount + 1): # left to right: a coin can be reused
dp[c] += dp[c - coin]
return dp[amount] // 0/1 knapsack: each item at most once, so capacity goes right to left
int knapsack(int W, vector<int>& val, vector<int>& wt) {
vector<int> dp(W + 1, 0); // dp[c] = best value with capacity c
for (int i = 0; i < (int)wt.size(); i++)
for (int c = W; c >= wt[i]; c--)
dp[c] = max(dp[c], dp[c - wt[i]] + val[i]);
return dp[W];
}
// Coin Change: fewest coins (unbounded, left to right)
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1); // amount + 1 acts as infinity
dp[0] = 0;
for (int c = 1; c <= amount; c++)
for (int coin : coins)
if (coin <= c) dp[c] = min(dp[c], dp[c - coin] + 1);
return dp[amount] > amount ? -1 : dp[amount];
}
// Coin Change II: number of combinations
int change(int amount, vector<int>& coins) {
vector<unsigned long long> dp(amount + 1, 0); // unsigned: intermediate counts may be large
dp[0] = 1;
for (int coin : coins)
for (int c = coin; c <= amount; c++)
dp[c] += dp[c - coin];
return (int)dp[amount];
} // 0/1 knapsack: each item at most once, so capacity goes right to left
function knapsack(W, val, wt) {
const dp = new Array(W + 1).fill(0); // dp[c] = best value with capacity c
for (let i = 0; i < wt.length; i++)
for (let c = W; c >= wt[i]; c--) dp[c] = Math.max(dp[c], dp[c - wt[i]] + val[i]);
return dp[W];
}
// Coin Change: fewest coins (unbounded, left to right)
function coinChange(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let c = 1; c <= amount; c++)
for (const coin of coins) if (coin <= c) dp[c] = Math.min(dp[c], dp[c - coin] + 1);
return dp[amount] === Infinity ? -1 : dp[amount];
}
// Coin Change II: number of combinations (coins in the outer loop)
function change(amount, coins) {
const dp = new Array(amount + 1).fill(0);
dp[0] = 1; // one way to make 0: take nothing
for (const coin of coins)
for (let c = coin; c <= amount; c++) dp[c] += dp[c - coin];
return dp[amount];
} The variations
-
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.Now you solve -
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- Perfect Squares Medium Stuck? ▶ video
-
3Coins: fewest coins, or number of ways
Fewest coins:
dp[c] = min(dp[c - coin] + 1), starting from infinity withdp[0] = 0. Number of ways:dp[c] += dp[c - coin]withdp[0] = 1, and coins in the outer loop so each combination is counted once.Now you solve- Coin Change II Medium Stuck? ▶ video
-
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.
Lesson done
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.