Knapsack and Subset DP

Master 0/1 knapsack, unbounded knapsack and subset-sum variants, the most reused DP template in placement tests.

Intermediate · about 7 hours · difficulty 4/5

Learn first: 2D DP and DP on Grids

Knapsack is the template behind a large share of DP questions. Once you see "pick or not pick with a capacity", you know the state is (index, remaining capacity).

0/1 knapsack

dp[i][w] = max(dp[i - 1][w], value[i] + dp[i - 1][w - weight[i]]). Each item is used at most once. With one 1D array, loop capacity downwards so an item is not reused.

Unbounded knapsack

Items can be reused: dp[i][w] uses dp[i][w - weight[i]] (same row). With a 1D array, loop capacity upwards. Coin Change, Rod Cutting and Coin Change II are unbounded knapsacks.

Subset-sum family

  • Subset Sum Equal to Target (boolean DP).
  • Partition Equal Subset Sum: target = total / 2.
  • Count subsets with sum k, Partition with given difference (reduce to counting subsets with sum (total + d) / 2).
  • Target Sum: the same reduction with plus and minus signs.
  • Minimum subset sum difference: fill the subset-sum table, then scan the last row.

Pitfalls

  • Zeros in the array break count-of-subsets unless the base case handles them.
  • Large capacities (1e9) make the table infeasible; look for a different state, like DP over value instead of weight.
  • Loop direction mistakes in the 1D version.

You are ready to move on when you can reduce Target Sum to a count-subsets problem and explain why the 1D 0/1 knapsack loops capacity downwards.

Key concepts

  • 0/1 knapsack
  • Unbounded knapsack
  • Subset sum
  • Partition problems
  • Counting subsets with a target
  • 1D space optimisation and loop direction
  • DP over value for large capacity

Mini project

Solve these 10 in 7 days, log time and pattern: Subset Sum Problem (GfG), Partition Equal Subset Sum, Partition a Set Into Two Subsets with Minimum Difference, Perfect Sum Problem (GfG), Partitions with Given Difference (GfG), 0/1 Knapsack, Target Sum, Coin Change II, Rod Cutting (GfG), Knapsack 2 (AtCoder DP E).

Check yourself

Why does the 1D array version of 0/1 knapsack iterate capacity from high to low, while unbounded knapsack iterates low to high?

Free resources