mediumDynamic ProgrammingDynamic Programming

0/1 Knapsack

mediumTime: O(n * W)Space: O(n * W)

Signals to notice

maximize value within weight capacityeach item used at most onceinclude or exclude

Brute force first

Try all 2^n subsets, check weight and maximize value. Exponential in the number of items. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

2D DP: dp[i][w] = max value using items 1.i with capacity w. For each item: either skip it (dp[i-1][w]) or include it (dp[i-1][w-weight[i]] + value[i]). Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

dp[i][w] considers only items up to index i and exactly capacity w. Each item is either included (reducing remaining capacity) or excluded (keeping capacity). The better choice is taken. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Using the item more than once — 0/1 means each item is available exactly once. Process items in order and reference dp[i-1][..] (previous row) to prevent reuse. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern