Algorithms

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?

9 minLevel 3/3The interactive stage stays ad-free.
Try:
5 items · capacity 8
Capacity8Items5Best value11Step54 / 54
Item012345678
∅000000000
A (2kg)003333333
B (3kg)003447777
C (4kg)003457899
D (5kg)0034578910
E (1kg)02356791011

Item E, capacity 8: best value 11.

Skip the item and keep 10; take it and add 2 to 9, giving 11.

Best value 11B (3kg, 4) · C (4kg, 5) · E (1kg, 2)

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

1

Rows are items, columns are capacities. dp[i][w] is the best value using items up to i and capacity w.

2

For each item, either skip it (take the cell above) or take it if it fits (value plus the cell at w - weight).

3

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.