The Knapsack Problem
The 0/1 Knapsack Problem is a cornerstone of combinatorial optimization. A burglar has a knapsack of capacity \(W\) and \(n\) items — each with a weight \(w_i\) and value \(v_i\). Which items maximize total value without exceeding capacity? Each item can be taken at most once (0 or 1).
A brute-force approach tries all \(2^n\) subsets — exponential! DP exploits overlapping subproblems and optimal substructure to solve it in \(O(nW)\) time.
Problem Formalization
Maximize: \(\displaystyle\sum_{i=1}^{n} v_i x_i\)
Subject to: \(\displaystyle\sum_{i=1}^{n} w_i x_i \leq W\), \quad \(x_i \in \{0,1\}\)
where \(x_i = 1\) means item \(i\) is taken.
Worked Example
Variants Overview
| Variant | Constraint | Method | Real-World |
|---|---|---|---|
| 0/1 Knapsack | Each item: 0 or 1 times | DP \(O(nW)\) | Project portfolio selection |
| Bounded Knapsack | Item \(i\) at most \(k_i\) times | DP + binary split | Inventory allocation |
| Unbounded Knapsack | Item \(i\) unlimited times | DP \(O(nW)\) | Coin change, rod cutting |
| Fractional Knapsack | Items divisible | Greedy \(O(n\log n)\) | Liquid/bulk commodity loading |
| Multi-dimensional | Multiple weight constraints | DP multi-table | Budget + time constraints |