How the 0/1 knapsack works
dp[i][w] is the best value you can get from the first i items with capacity w. If item i does not fit, the answer is the same as without it: dp[i − 1][w]. If it fits, take the better of skipping it, dp[i − 1][w], and taking it, dp[i − 1][w − weight] + value. Fill the table row by row; the last cell is the answer.
The example has weights [1, 3, 4], values [15, 20, 30] and capacity 5. The best choice is the first and third items: weight 5, value 45.
What to watch for when it runs
- The table is drawn as a grid, and each new cell reads only from the row above it.
- Taking an item reads the row above, shifted back by that item’s weight.
- The bottom-right cell is the answer.
Time and space complexity
- Time
- O(n × W)
- Space
- O(n × W), or O(W) with a single row
n is the number of items and W the capacity. That is pseudo-polynomial: fast for small capacities, but it grows with the value of W, not its number of digits.