Dynamic programmingAnimated
0/1 Knapsack
For each item choose take or skip to maximise value within capacity.
Time
O(n · W)
Extra space
O(W)
Use it for
Resource allocation with indivisible items.
How it works
- Each item can be taken once or not at all. Maximise total value without exceeding the capacity.
- Table cell (i, c) = best value using the first i items with capacity c.
- For item i: either skip it (cell above) or take it (value[i] + the cell above at capacity c − weight[i]); keep the larger.
- Fill row by row. Walk back through the table to see which items were taken. O(items × capacity).
Watch it run
Loading animation…