Knapsack problems
The 0-1 knapsack asks for the most value that fits when each item is taken whole or not at all; DP fills a table dp[i][j] (first i items, capacity j), and in one row the inner loop must run backwards, since forwards gives the complete knapsack.
You're travelling, and the bag holds at most 6 kg. A book weighs 2 and is worth 3, a camera weighs 3 and is worth 4, a laptop weighs 4 and is worth 5: what should you take for the most value? 3 items can be taken only 8 ways, so just try them all; 30 items can be taken 2³⁰ ways, over a billion. This is the 0-1 knapsack: each item is taken (1) or left (0), never half of it (the "fractional knapsack", where halves are allowed, is solved greedily). Dynamic programming turns it into filling a 31 × 7 table.
The 2D table: take it or leave it
The four steps:
- State: dp[i][j] = the most value from just the first i items with capacity j;
- Transition: item i (weight w, value v) has only two choices. Leave it: the answer is the same as with the first i − 1 items, dp[i − 1][j]; take it (needs j ≥ w): set w aside for it and give the remaining j − w to the first i − 1 items, dp[i − 1][j − w] + v. Take the bigger,
max(…, …); - Initial values: row 0 (no items) and column 0 (capacity 0) are all 0;
- Order: row by row from the top, each row left to right; everything needed is in the row above.
The table has (n + 1) × (W + 1) boxes at O(1) each: O(nW) time. Note that W is the capacity's value, not the length of the input: with a capacity of a billion the table can't be filled (which is why the 0-1 knapsack still counts as a "hard" problem).
Try one box yourself: capacity 4, three items (weight 1 value 2) (weight 2 value 3) (weight 3 value 4), and the table filled in up to its last box.
What goes in the question-mark box, dp[3][4] (the first 3 items, capacity 4)?
With n = 100 items and capacity W = 1000, roughly how many boxes does the 2D table have?
Fill in the 2D table
✓Finish the 0-1 knapsack's 2D transition: leaving it copies straight above; when it fits, taking it is dp[i − 1][j − w[i]] + v[i], take the bigger. Print the answers for capacity 5 and 8.
7 10
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6vector<int> w = {0, 2, 3, 4, 5};7vector<int> v = {0, 3, 4, 5, 6};8 9int best(int W) {10 int n = w.size() - 1;11 vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));12 for (int i = 1; i <= n; i++)13 for (int j = 0; j <= W; j++) {14 // leave it: dp[i - 1][j]; when j >= w[i], compare with taking it15 }16 return dp[n][W];17}18 19int main() {20 cout << best(5) << " " << best(8) << "\n";21 return 0;22}
Reading back: which items were taken
The table only says the most value is 8. To find what was taken, walk back from the bottom-right: if dp[i][j] equals dp[i − 1][j] straight above, item i wasn't taken (leaving it does as well); if it's different, it was taken: take its weight off the capacity and carry on in the row above.
In C++ the table is vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0)): n + 1 rows, each a vector of W + 1 boxes, all 0.
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int main() {8 int n = 3, W = 6;9 vector<int> w = {0, 2, 3, 4}; // indexes from 1, lined up with the table's rows10 vector<int> v = {0, 3, 4, 5};11 vector<string> name = {"", "book", "camera", "laptop"};12 vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));13 14 for (int i = 1; i <= n; i++)15 for (int j = 0; j <= W; j++) {16 dp[i][j] = dp[i - 1][j]; // leave it17 if (j >= w[i]) dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i]); // take it18 }19 for (const vector<int>& row : dp) {20 for (int x : row) cout << (x < 10 ? " " : "") << x << " "; // pad to two wide21 cout << "\n";22 }23 cout << "Most value " << dp[n][W] << ", taken: ";24 int j = W;25 for (int i = n; i >= 1; i--)26 if (dp[i][j] != dp[i - 1][j]) { // different from above: taken27 cout << name[i] << " ";28 j -= w[i];29 }30 cout << "\n";31 return 0;32}
0 0 0 0 0 0 0 0 0 3 3 3 3 3 0 0 3 4 4 7 7 0 0 3 4 5 7 8 Most value 8, taken: laptop book
Three items (weight 1 value 2) (weight 2 value 3) (weight 3 value 4), capacity 4. Once the table is filled, reading back from the bottom right prints what?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 int n = 3, W = 4;8 vector<int> w = {0, 1, 2, 3};9 vector<int> v = {0, 2, 3, 4};10 vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));11 for (int i = 1; i <= n; i++)12 for (int j = 0; j <= W; j++) {13 dp[i][j] = dp[i - 1][j];14 if (j >= w[i]) dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i]);15 }16 int j = W;17 for (int i = n; i >= 1; i--)18 if (dp[i][j] != dp[i - 1][j]) {19 cout << i << " ";20 j -= w[i];21 }22 cout << "\n";23 return 0;24}
Fill in the condition for reading back: different from straight above means this item was taken. The program prints the numbers of the items taken (the book, camera and laptop are 1, 2 and 3).
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 int n = 3, W = 6;8 vector<int> w = {0, 2, 3, 4};9 vector<int> v = {0, 3, 4, 5};10 vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));11 for (int i = 1; i <= n; i++)12 for (int j = 0; j <= W; j++) {13 dp[i][j] = dp[i - 1][j];14 if (j >= w[i]) dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i]);15 }16 int j = W;17 for (int i = n; i >= 1; i--)18 if (dp[i][j] dp[i - 1][j]) {19 cout << i << " ";20 j -= w[i];21 }22 cout << "\n";23 return 0;24}
!=: different from straight above means leaving it couldn't reach that much, so it must have been taken. With ==, it prints the ones left behind instead (and the capacity never goes down, so everything after goes wrong); with <, it's never true and nothing is printed.Down to one row: the inner loop runs backwards
Each row uses only the row above, so keep just one row vector<int> dp(W + 1) and update it in place, one item at a time:
1for (int i = 1; i <= n; i++)2 for (int j = W; j >= w[i]; j--) // backwards3 dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
Updating dp[j] reads dp[j − w], which should still hold the row above (the value without this item). Backwards, the boxes to the left haven't been updated for this item yet, so the read gets the old value; forwards, the box to the left has just had this item put in, and reading it takes the same item a second time.
With all three items, run each direction once:
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int n = 3, W = 6;7vector<int> w = {0, 2, 3, 4};8vector<int> v = {0, 3, 4, 5};9 10int solve(bool backward) {11 vector<int> dp(W + 1, 0);12 for (int i = 1; i <= n; i++) {13 if (backward) {14 for (int j = W; j >= w[i]; j--) // backwards: the 0-1 knapsack15 dp[j] = max(dp[j], dp[j - w[i]] + v[i]);16 } else {17 for (int j = w[i]; j <= W; j++) // forwards: one item can be taken many times18 dp[j] = max(dp[j], dp[j - w[i]] + v[i]);19 }20 }21 for (int x : dp) cout << x << " ";22 cout << "\n";23 return dp[W];24}25 26int main() {27 cout << "Backwards: ";28 int a = solve(true);29 cout << "Forwards: ";30 int b = solve(false);31 cout << "backwards " << a << ", forwards " << b << "\n";32 return 0;33}
Backwards: 0 0 3 4 5 7 8 Forwards: 0 0 3 4 6 7 9 backwards 8, forwards 9
Backwards gives 8, the same as the 2D table. Forwards gives 9: three books (weight 6), when we have only one. One loop direction and the answer is wrong, with no error from the compiler or at run time.
Capacity 7, four items (weight 1 value 1) (weight 3 value 4) (weight 4 value 5) (weight 5 value 7), each taken at most once. What is the most value?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> w = {1, 3, 4, 5};8 vector<int> v = {1, 4, 5, 7};9 vector<int> dp(8, 0);10 for (int i = 0; i < 4; i++)11 for (int j = 7; j >= w[i]; j--)12 dp[j] = max(dp[j], dp[j - w[i]] + v[i]);13 cout << dp[7] << "\n";14 return 0;15}
Pick one for the for's parentheses so that it's the 0-1 knapsack (each item taken at most once) and prints 8.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> w = {2, 3, 4};8 vector<int> v = {3, 4, 5};9 vector<int> dp(7, 0);10 for (int i = 0; i < 3; i++) {11 int wi = w[i], vi = v[i];12 for (int j = )13 dp[j] = max(dp[j], dp[j - wi] + vi);14 }15 cout << dp[6] << "\n";16 return 0;17}
Two halves with equal sums
✓Can the array be split into two groups with equal sums? An odd total can't; otherwise the question is whether some of the numbers add up to exactly half the total. can[j] means "j can be made", and each number is used at most once: the inner loop runs backwards.
1 0
1#include <iostream>2#include <vector>3#include <numeric>4using namespace std;5 6bool split(const vector<int>& a) {7 int sum = accumulate(a.begin(), a.end(), 0);8 if (sum % 2) return false;9 int half = sum / 2;10 vector<bool> can(half + 1, false);11 can[0] = true;12 // for each x: j from half down to x; if can[j - x] is true, make can[j] true13 return can[half];14}15 16int main() {17 cout << split({1, 5, 11, 5}) << " " << split({1, 2, 3, 5}) << "\n";18 return 0;19}
The complete knapsack: forwards
If each kind of item comes in unlimited supply, take as many as you like, it's the complete knapsack. Now "the same item many times" is exactly what we want: make the inner loop run forwards, and change nothing else. The "wrong" forwards run above was in fact the complete knapsack's answer, 9.
| 0-1 knapsack | Complete knapsack | |
|---|---|---|
| Each kind | At most 1 | Any number |
| 2D transition (the take term) | dp[i − 1][j − w] + v (the row above) | dp[i][j − w] + v (the same row) |
| 1D inner loop | j from W down to w, backwards | j from w up to W, forwards |
| Typical problems | Equal-sum partition, target sum | Coin change (fewest coins, number of ways) |
The "fewest coins" problem from the last lesson is a complete knapsack: each coin can be used any number of times.
In exams: "fill in the 0-1 knapsack table", "write the transition", "time complexity O(nW)" come up a lot. In interviews a knapsack often doesn't say "knapsack": "can the array be split into two halves with equal sums" is a 0-1 knapsack (capacity = half the total), "how many ways to make the amount" is a complete knapsack. Recognise which one first, then pick the loop direction.
"The fewest coins of 1, 2 and 5 that make 11" and "can the array {1, 5, 11, 5} be split into two halves with equal sums": which knapsack is each?
With coins of 1, 2 and 5 (as many of each as you like), how many ways are there to make 5?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> coins = {1, 2, 5};7 vector<int> ways(6, 0);8 ways[0] = 1;9 for (int c : coins)10 for (int j = c; j <= 5; j++)11 ways[j] += ways[j - c];12 cout << ways[5] << "\n";13 return 0;14}
With the STL
C++ code writes this table three common ways, all O(nW); they differ in space and in whether you can read back:
- 2D
vector<vector<int>>:dp(n + 1, vector<int>(W + 1, 0)). The outer vector holds n + 1 vectors, each row its own contiguous block. It takes (n + 1)(W + 1) ints and can be read back. - Two rolling rows: keep only
prevandcur, and after each rowswap(prev, cur). A vector'sswapexchanges just the three pointers inside, O(1), no data copied;prev = curwould be an O(W) copy. The transition is exactly the 2D one, and the inner loop can go either way. - One row backwards:
vector<int> dp(W + 1), the smallest, but the inner loop must run backwards and it can't be read back.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <utility>5using namespace std;6 7int main() {8 vector<int> w = {3, 4, 5, 2, 6, 7, 1, 8};9 vector<int> v = {4, 5, 7, 3, 8, 9, 1, 10};10 int n = w.size(), W = 20;11 12 // 1. The 2D table: row i uses item i - 1 (w[i - 1])13 vector<vector<int>> dp2(n + 1, vector<int>(W + 1, 0));14 for (int i = 1; i <= n; i++)15 for (int j = 0; j <= W; j++) {16 dp2[i][j] = dp2[i - 1][j];17 if (j >= w[i - 1]) dp2[i][j] = max(dp2[i][j], dp2[i - 1][j - w[i - 1]] + v[i - 1]);18 }19 20 // 2. Two rolling rows: swap exchanges pointers only21 vector<int> prev(W + 1, 0), cur(W + 1, 0);22 for (int i = 0; i < n; i++) {23 for (int j = 0; j <= W; j++) {24 cur[j] = prev[j];25 if (j >= w[i]) cur[j] = max(cur[j], prev[j - w[i]] + v[i]);26 }27 swap(prev, cur); // the row just done becomes "the row above"28 }29 30 // 3. One row, backwards31 vector<int> dp1(W + 1, 0);32 for (int i = 0; i < n; i++)33 for (int j = W; j >= w[i]; j--)34 dp1[j] = max(dp1[j], dp1[j - w[i]] + v[i]);35 36 cout << "2D table " << dp2[n][W] << ", " << (n + 1) * (W + 1) << " boxes\n";37 cout << "Two rows " << prev[W] << ", " << 2 * (W + 1) << " boxes\n";38 cout << "One row backwards " << dp1[W] << ", " << W + 1 << " boxes\n";39 return 0;40}
2D table 27, 189 boxes Two rows 27, 42 boxes One row backwards 27, 21 boxes
All three give the same answer. Note that after the swap the row just finished is in prev, so the answer is prev[W].
| Way | Space | Inner loop | Read back |
|---|---|---|---|
vector<vector<int>> 2D table | O(nW) | Either way | Yes |
Two rows + swap | O(W) | Either way | No |
One row vector<int> | O(W) | 0-1 backwards, complete forwards | No |
Two more C++ traps: don't swap the two sizes in vector<vector<int>> dp(n + 1, vector<int>(W + 1)), or dp[i][j] runs out of bounds without an error; and when the values can add up past an int (about 2.1 billion), make the table long long.
In interviews: A knapsack often isn't called one: "can the array be split into two halves with equal sums" is a 0-1 knapsack (capacity = half the total), "how many ways make the amount" is a complete knapsack. Recognise which kind first, then pick the loop direction. Asked to save space, say "each row uses only the row above, so it fits in one row; the 0-1 knapsack's inner loop runs backwards so it reads the old values of the row above". Course exams often ask you to "fill in the 0-1 knapsack table", "write the transition" and "the time complexity is O(nW)".
With two rolling rows, each finished row ends with swap(prev, cur) rather than prev = cur. Why?
swap moves no data: it only swaps which block of memory each one points to, so it is O(1). prev = cur really copies, O(W) per row, adding O(nW) copying in all, as much as filling the table itself. Both give the same answer; the difference is speed.Summary
The knapsack: take it or leave it, whichever is bigger
- dp[i][j]: the most value from the first i items with capacity j; O(nW) time
- Leave it dp[i − 1][j], take it dp[i − 1][j − w] + v, take the max
- Reading back: different from straight above means taken; take its weight off
- One row: the 0-1 knapsack's inner loop runs backwards; forwards is the complete knapsack
- Two rolling rows with swap(prev, cur): O(1), nothing copied
1vector<int> dp(W + 1, 0);2for (int i = 1; i <= n; i++)3 for (int j = W; j >= w[i]; j--)4 dp[j] = max(dp[j], dp[j - w[i]] + v[i]);