Why it matters

Knapsack appears in many resource allocation problems. Understanding DP approach opens up broader class.

Advertisement

The architecture

DP: dp[i][w] = max value using first i items with weight ≤ w.

Transition: don't take item i (dp[i-1][w]) vs take it (dp[i-1][w - weight_i] + value_i).

Knapsack DPConsider item iat capacity wTake or skipmax of twoFill tablebottom-upPseudo-polynomial: O(nW) where W = capacity; not truly polynomial
Knapsack recurrence.
Advertisement

How it works end to end

Fractional knapsack: greedy works (take highest value-per-weight first).

Unbounded knapsack: unlimited of each item. Different DP.

Multi-dimensional: constraints on multiple resources. More complex DP.

Applications: budget allocation, resource scheduling, project selection.