The 0/1 Knapsack Problem is a classic combinatorial optimization problem. Given items, each with a specific weight and value , and a knapsack with maximum weight capacity , determine the maximum total value of items that can fit in the knapsack.
Unlike the fractional knapsack problem (which can be solved greedily), 0/1 Knapsack requires Dynamic Programming (DP) because items cannot be broken into fractions.
1. Summary & Key Takeaways
- Sub-Problem Recurrence Relation:
- State Definition: represents the maximum value achievable considering the first items with capacity .
- Time Complexity: pseudo-polynomial time (where is item count and is capacity).
- Space Complexity: using a full 2D table, or space using 1D space optimization.
2. Interactive Knapsack Playground
Use the interactive memoization matrix below to step through sub-problem evaluations cell-by-cell!
Click Step 1 DP Cell to watch the matrix evaluate whether including the current item yields higher total value than excluding it!
0/1 Knapsack Dynamic ProgrammingMemoization Matrix
Fill the 2D DP matrix DP[i][w] = max(DP[i-1][w], val[i] + DP[i-1][w-wt[i]]) cell-by-cell!
| Item \ Wt | W=0 | W=1 | W=2 | W=3 | W=4 | W=5 | W=6 | W=7 |
|---|---|---|---|---|---|---|---|---|
| No Items | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Gemstone | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Gold Bar | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Artifact | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| Crown | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
# 0/1 Knapsack Dynamic Programming in Python
def knapsack(W, weights, values):
n = len(values)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(W + 1):
if weights[i - 1] <= w:
dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
else:
dp[i][w] = dp[i - 1][w]
return dp[n][W]3. Formulated Memoization Matrix Solution
For the sample catalog below ():
- Gemstone: Weight , Value =\3$
- Gold Bar: Weight , Value =\4$
- Artifact: Weight , Value =\5$
- Crown: Weight , Value =\8$
Here is the completed state matrix:
| Item \ Wt | W=0 | W=1 | W=2 | W=3 | W=4 | W=5 | W=6 | W=7 |
|---|---|---|---|---|---|---|---|---|
| No Items | ||||||||
| Gemstone | \3$ | \3$ | \3$ | \3$ | \3$ | \3$ | ||
| Gold Bar | \3$ | \4$ | \4$ | \7$ | \7$ | \7$ | ||
| Artifact | \3$ | \4$ | \5$ | \7$ | \8$ | \9$ | ||
| Crown | \3$ | \4$ | \5$ | \8$ | \8$ | \11$ |
At capacity , the optimal combination takes the Crown (W=5, V=\8W=2, V=$3$11$**!
4. Knapsack Variants Matrix
| Variant | Fractional Split Allowed? | Optimal Strategy | Time Complexity |
|---|---|---|---|
| 0/1 Knapsack | ❌ No (Take item whole or leave) | Dynamic Programming | |
| Fractional Knapsack | ✅ Yes (Take fractions of items) | Greedy Algorithm (Value/Weight ratio) | |
| Unbounded Knapsack | ❌ No (Unlimited duplicate items) | Dynamic Programming (1D array) |