Why it matters

Knapsack is classic DP. Understanding shapes combinatorial optimization.

Advertisement

The architecture

dp[i][w] = max value using first i items with weight <= w.

Include or exclude item i.

Knapsack DPItem iconsiderExcludedp[i-1][w]Includedp[i-1][w-w_i] + v_iSpace O(W) with rolling; unbounded knapsack allows repeats
Knapsack.
Advertisement

How it works end to end

Base: dp[0][w] = 0.

Transitions: max of include/exclude.

Space O(W) with rolling right-to-left.

FPTAS approximates in poly(1/epsilon).