Algorithms Playbook
PatternTime O(n · W) · Space O(W)9 min read

The 0/1 knapsack: choosing items under a limit

Pick items with a weight and a value to get the most value without exceeding a capacity. The table, the 1D trick, and the many interview problems that are knapsack in disguise.

In short

For each item you decide take it or leave it (once). Let dp[c] be the best value with capacity c; for each item, update c from high to low: dp[c] = max(dp[c], dp[c − w] + v). Time O(n · W), space O(W).

The idea: two choices per item

A bag holds 5 kg. Items weigh and are worth different amounts. The best choice for the first i items with capacity c is either skip item i (the best for the first i−1 items) or take it (its value plus the best for i−1 items with capacity c − weight).

0/1 knapsack: take it or leave it, once
Speed
001020304050dp[c] = best value with capacity c (total capacity 5)

items (weight → value)

02→313→424→5
1def knapsack(weights, values, cap):
2 dp = [0] * (cap + 1)
3 for i in range(len(weights)):
4 for c in range(cap, weights[i] - 1, -1):
5 dp[c] = max(dp[c], dp[c - weights[i]] + values[i])
6 return dp[cap]
dp[c] = best total value using capacity c. With no items yet, every capacity gives 0.

Variables

cap5
Step 1/14· Updates: 0
Why does `c` go downwards? dp[c − w] must still hold the value from BEFORE this item. Going upwards would let one item be counted twice, which is the unbounded knapsack (like coin change).

The 1D trick: go downwards

The full table is dp[i][c], but row i only reads row i−1, so a single array is enough, if you loop the capacity downwards. Then dp[c − w] still holds the value from before this item, so the item is counted at most once.

0/1 knapsack

  • Each item once
  • Capacity loop goes down
  • Example: partition, subset sum

Unbounded knapsack

  • Each item any number of times
  • Capacity loop goes up
  • Example: coin change

Knapsack in disguise

Problem"Capacity""Value"
Subset sum / can you reach exactly S?The target sum Strue / false
Partition into two equal halvesHalf of the total sumtrue / false
Maximum loot within a budgetBudgetSum of values
Number of ways to reach a targetTargetCount (add instead of max)

Key takeaways

  • 01Per item: skip it, or take it and add its value to the best of the remaining capacity.
  • 02A single dp array works if the capacity loop goes from high to low.
  • 03Loop upwards instead and you get the unbounded version (coin change).
  • 04Subset sum and partition are the same table with true/false.

Check your understanding

1 of 3

In the 0/1 knapsack, what are the two options for an item?

Related topics