AlgoScope

0/1 Knapsack

Algorithmintermediate2D Dynamic Programming

dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt] + val); each item is taken at most once.

Decision · step 3 of 34Knapsack: 0/1 knapsack, capacity 7
012345670i1i2i3i4000✓0✓0✓0✓0✓0✓0✓1✓

Item 1 (weight 1, value 1) at capacity 1. Skip: 0 from above. Take: 1 + 0 from the previous row at capacity 0 = 1. Best: 1, take.

Open in the player →or start at step 3

What you will see

Row per item, column per capacity; each cell reads the cell above and the cell above-left by the item's weight.

How knapsack works →

Cost

BestO(n * W)
AverageO(n * W)
WorstO(n * W)
SpaceO(W)

Pseudo-polynomial in W; O(W) space with a single row iterated right to left.

How you work with it here

play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.

Screen readers: Table cells announce their state and value; each step announces which cells were read and the value written.

Reduced motion: Dependency arrows appear statically and the cell value crossfades.

Before this

Leads to

Topics that need this one first.

Taught by the same lesson

Knapsack covers these too, in the same run.