Builds onDynamic programming in one dimension
01The idea
In a knapsack problem you have items, each with a weight and a value, and a bag that can hold a limited total weight. You pick a set of items to get the most value without going over the limit. In the 0/1 version, each item is either taken once or left behind.
Trying every set of items takes O(2ⁿ). DP does better by looking at one item at a time. For each item and each capacity c, there are two choices:
- Skip the item. The best value stays what it was without this item.
- Take the item. Its value, plus the best value for the capacity that is left,
c - weight.
Keep the larger. So best[c] = max(best[c], best[c - w] + v).
You can store this as a 2D table, one row per item. Each row only reads the row before it, so a single array is enough, as long as you update it in the right direction. Go from the largest capacity down to the smallest. Then best[c - w] still holds the value from before the current item, and the item cannot be counted twice.
If an item may be taken any number of times, go upward instead. Then best[c - w] may already include the item, which is exactly what you want.
02How to spot it
Knapsack DP fits when:
- you choose a subset of items under a limit on a total, such as weight, cost, time or a sum
- the question asks for the best value, the number of ways, or whether a total can be reached exactly
- the limit is a small enough number to index an array, such as up to 10,000
Many problems are knapsacks in disguise. "Can this list be split into two parts with equal sums?" asks whether some subset adds up to half the total. "How many ways can you make an amount from these coins?" counts combinations under a sum.
The question to ask is whether each item can be used once or many times. That sets the direction of the inner loop.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue