Knapsack DP
Pick items under a capacity, a target sum or a budget with one table indexed by capacity. The 0/1 and unbounded variants differ by one loop direction, and most subset-sum, coin and partition problems are knapsacks in disguise.
Overview
The problem
You have items, each with a weight and a value, and a bag that holds at most a fixed total weight, the capacity. Which items give the largest total value without going over? In the 0/1 knapsack each item is taken once or not at all. In the unbounded knapsack you may take any number of copies of an item.
The rest of this topic traces one small instance with three items. Item A weighs 2 and is worth 3, item B weighs 3 and is worth 4, and item C weighs 1 and is worth 2. The capacity is 5.
The choices that fit are A + B (weight 5, value 7), B + C (weight 4, value 6) and A + C (weight 3, value 5). All three together weigh 6 and do not fit. The best value is 7.
Trying every subset works for three items, but there are 2ⁿ subsets: for 40 items that is about 1.1 trillion. Dynamic programming replaces the subsets with a table that has one cell per (item, capacity) pair.
The table works because each item is one decision with two moves. Skipping item i keeps the capacity c and the value you have. Taking it spends its weight, leaving capacity c − weight, and adds its value. The table stores the best result of each move, so no branch is explored twice.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio