mediumDynamic ProgrammingDynamic Programming

0/1 Knapsack

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

Recognize the pattern

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

Brute force idea

If you approach 0/1 Knapsack in the most literal way possible, you get this: 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.

Better approach

The deeper shift in 0/1 Knapsack is this: 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.

Key invariant

At the center of 0/1 Knapsack is one steady idea: 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.

Watch out for

The trap in 0/1 Knapsack usually looks like this: 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