Skip to content

Knapsack Playground

Change the capacity or the items and watch the 0/1 knapsack table compute the best value

1. The playground

Rows are items and columns are capacities. Each cell stores the best value for that prefix of items and that capacity. Press Animate fill to watch the table compute row by row; the bottom-right cell is the answer, and the readout lists the chosen items.

2. What to notice

  • Each row either copies the row above (skip the item) or adds the item's value to a cell with less capacity (take it).
  • A heavier item can beat several lighter items, or lose to them. The table compares the choices instead of guessing.
  • The final value is in the bottom-right cell. The chosen items come from walking backward and checking whether the value changed from the row above.
  • The running time is O(items × capacity). A huge numeric capacity makes this table impractical even when the item count is small.

3. The recurrence

The state is the item index and the remaining capacity. The transition chooses the better of skipping the item and taking it.

0/1 knapsack

Space can be reduced to one row by iterating capacity downward, so each item is used at most once. The full table is kept here because the point is to see the choices.

4. Related lessons

Site soundtrack