0-1 Knapsack DP
Watch the classic knapsack DP table fill in. Each cell answers: what is the best value using the first i items with capacity w?
| Item | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A (2kg) | 0 | 0 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |
| B (3kg) | 0 | 0 | 3 | 4 | 4 | 7 | 7 | 7 | 7 |
| C (4kg) | 0 | 0 | 3 | 4 | 5 | 7 | 8 | 9 | 9 |
| D (5kg) | 0 | 0 | 3 | 4 | 5 | 7 | 8 | 9 | 10 |
| E (1kg) | 0 | 2 | 3 | 5 | 6 | 7 | 9 | 10 | 11 |
Item E, capacity 8: best value 11.
Skip the item and keep 10; take it and add 2 to 9, giving 11.
Each cell compares skipping the current item with taking it plus the best earlier result. Edit the items or capacity to turn this into a small planning tool. After completion, Trace winners follows the chosen cells back through the table.
What you are seeing
Rows are items, columns are capacities. dp[i][w] is the best value using items up to i and capacity w.
For each item, either skip it (take the cell above) or take it if it fits (value plus the cell at w - weight).
After the table is full, trace backward from the bottom-right cell to see which items were chosen.
Why it matters
Knapsack is the gateway to dynamic programming: resource allocation, budgeting, scheduling, and many optimization problems share the same table-filling structure.
Complexity & details
Time: O(nW), space: O(nW) for the full table (O(W) with rolling arrays).
Frequently asked questions
Why is knapsack pseudo-polynomial?+
The runtime depends on the numeric capacity W, not just the number of items. A large W makes the table large even when the input count is small.
What does the backtracking step do?+
Starting from dp[n][W], if the value came from the current item, include it and move to w - weight; otherwise move up one row.