Skip to content
StackDecode
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

  1. Each item can be taken once or not at all. Maximise total value without exceeding the capacity.
  2. Table cell (i, c) = best value using the first i items with capacity c.
  3. For item i: either skip it (cell above) or take it (value[i] + the cell above at capacity c − weight[i]); keep the larger.
  4. Fill row by row. Walk back through the table to see which items were taken. O(items × capacity).

Watch it run

Loading animation…