Command Palette

Search for a command to run...

Module 30

Knapsack DP

Choose items under a capacity: 0/1 and unbounded knapsack, subset sums, coin change, counting combinations vs permutations, and two-dimensional capacities.

Advanced 3 lessons 8 problems ~40 min of lessons

Knapsack problems ask which items to pick when there's a limit: a bag's weight, a target sum, an amount of money. The DP state adds the remaining capacity to the item index, and one loop direction decides whether each item can be used once or many times.

This module teaches the 0/1 knapsack table and its one-row version, the unbounded variant, and the family of problems that turn into it: equal partitions, target sums with + and −, splitting stones, coin change (fewest coins and number of ways), and capacities with two dimensions.

Best after: DP Foundations: 1D

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Boolean 0/1 knapsack towards total / 2.

  2. Algebra turns ± signs into counting subsets with sum (total + target) / 2.

  3. Recognising a hidden partition: the result is the difference between two groups.

  4. Unbounded knapsack minimising the number of items.

  5. Counting combinations: coins in the outer loop.

  6. Counting ordered sequences: amount in the outer loop.

  7. Coin change where the coins are 1, 4, 9, 16, …

  8. A knapsack with two capacities at once.