0 and 1 Knapsack
Pattern: Subsequences and knapsack
Each item has a weight and a value and may be taken once. best[c] is the most value with capacity c; for each item, update c from W down to its weight: best[c] = max(best[c], best[c - w] + v).
The problem
Given item weights wt, values val and a capacity W, return the largest total value of items (each used at most once) whose total weight is at most W.
Think first
- What are the choices for each item?
- What do you need to know about the items so far?
- Why does the loop direction matter?
Hints
Brute force, and why it fails
Try every subset: 2ⁿ.
The key insight
The best value for each capacity, item by item, holds everything needed.
Dry run
wt [1, 2, 4, 5], val [5, 4, 8, 6], W = 5.
Step 1 of 2
The plan
best = zeros(W + 1)
for each item: for c from W down to w: best[c] = max(best[c], best[c - w] + v)
return best[W]
Complexity
- Time
O(n × W)- Space
O(W)
One row.
Edge cases
- W = 0: 0.
- All items too heavy: 0.
- One item.
I've built my logic, show the code
Java
class Solution {
public int knapsack01(int[] wt, int[] val, int W) {
int[] best = new int[W + 1]; // best[c]: the most value with capacity c, using the items so far
for (int i = 0; i < wt.length; i++)
for (int c = W; c >= wt[i]; c--) best[c] = Math.max(best[c], best[c - wt[i]] + val[i]); // downwards: each item once
return best[W];
}
}C++
class Solution {
public:
int knapsack01(vector<int>& wt, vector<int>& val, int W) {
vector<int> best(W + 1, 0); // best[c]: the most value with capacity c, using the items so far
for (size_t i = 0; i < wt.size(); i++)
for (int c = W; c >= wt[i]; c--) best[c] = max(best[c], best[c - wt[i]] + val[i]); // downwards: each item once
return best[W];
}
};Python
class Solution:
def knapsack01(self, wt: list[int], val: list[int], W: int) -> int:
best = [0] * (W + 1) # best[c]: the most value with capacity c, using the items so far
for w, v in zip(wt, val):
for c in range(W, w - 1, -1): # downwards: each item once
best[c] = max(best[c], best[c - w] + v)
return best[W]Common mistakes
- Looping upwards.
- Greedy by value per weight, which fails for 0/1.