The knapsack problem
The 0-1 knapsack takes each item at most once for the most value within a capacity: dp[i][j] is the best from the first i items with capacity j, and in one row the inner loop over j must run from large to small, or an item is taken twice.
You're going travelling, and the backpack holds 6 kg at most. 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 is 2³⁰, over a billion ways. This is the 0-1 knapsack: each item is either taken (1) or not (0), never half of it (the "fractional knapsack", where half is allowed, is greedy: the exercise two lessons back). Dynamic programming turns it into filling a 30 × 7 table.
The 2D table: take it or leave it
The four steps:
- State: dp[i][j] = the most value possible using only the first i items with capacity j;
- Transition: item i (weight w, value v) has just two choices. Leave it: the answer is the same as with only the first i − 1 items, dp[i − 1][j]; take it (needs j ≥ w): set aside w for it and give the j − w left to the first i − 1 items, dp[i − 1][j − w] + v. Take the bigger of the two;
- Initial values: row 0 (no items yet) and column 0 (capacity 0) are all 0;
- Order: row by row top to bottom, 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 this 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
✓Complete 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 capacities 5 and 8.
7 10
1#include <stdio.h>2 3int n = 4;4int w[] = {0, 2, 3, 4, 5};5int v[] = {0, 3, 4, 5, 6};6int dp[5][9];7 8int best(int W) {9 for (int i = 1; i <= n; i++)10 for (int j = 0; j <= W; j++) {11 // leave it: dp[i - 1][j]; when j >= w[i], compare with taking it12 }13 return dp[n][W];14}15 16int main(void) {17 printf("%d ", best(5));18 printf("%d\n", best(8));19 return 0;20}
Reading back: which items were taken
The table only says the most value is 8. To know what was taken, walk back from the bottom right: if dp[i][j] is the same as dp[i − 1][j] straight above it, item i wasn't taken (leaving it already gets there); if it's different, it was taken, so take its weight off the capacity and go on in the row above.
1#include <stdio.h>2 3int n = 3, W = 6;4int w[] = {0, 2, 3, 4}; // from index 1, lined up with the table's rows5int v[] = {0, 3, 4, 5};6const char *name[] = {"", "book", "camera", "laptop"};7int dp[4][7];8 9int main(void) {10 for (int i = 1; i <= n; i++)11 for (int j = 0; j <= W; j++) {12 dp[i][j] = dp[i - 1][j]; // leave it13 if (j >= w[i] && dp[i - 1][j - w[i]] + v[i] > dp[i][j])14 dp[i][j] = dp[i - 1][j - w[i]] + v[i]; // take it15 }16 for (int i = 0; i <= n; i++) {17 for (int j = 0; j <= W; j++) printf("%2d ", dp[i][j]);18 printf("\n");19 }20 printf("most value %d, taken: ", dp[n][W]);21 int j = W;22 for (int i = n; i >= 1; i--)23 if (dp[i][j] != dp[i - 1][j]) { // different from above: taken24 printf("%s ", name[i]);25 j -= w[i];26 }27 printf("\n");28 return 0;29}
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 <stdio.h>2 3int n = 3, W = 4;4int w[] = {0, 1, 2, 3};5int v[] = {0, 2, 3, 4};6int dp[4][5];7 8int main(void) {9 for (int i = 1; i <= n; i++)10 for (int j = 0; j <= W; j++) {11 dp[i][j] = dp[i - 1][j];12 if (j >= w[i] && dp[i - 1][j - w[i]] + v[i] > dp[i][j])13 dp[i][j] = dp[i - 1][j - w[i]] + v[i];14 }15 int j = W;16 for (int i = n; i >= 1; i--)17 if (dp[i][j] != dp[i - 1][j]) {18 printf("%d ", i);19 j -= w[i];20 }21 printf("\n");22 return 0;23}
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 <stdio.h>2 3int n = 3, W = 6;4int w[] = {0, 2, 3, 4};5int v[] = {0, 3, 4, 5};6int dp[4][7];7 8int main(void) {9 for (int i = 1; i <= n; i++)10 for (int j = 0; j <= W; j++) {11 dp[i][j] = dp[i - 1][j];12 if (j >= w[i] && dp[i - 1][j - w[i]] + v[i] > dp[i][j])13 dp[i][j] = dp[i - 1][j - w[i]] + v[i];14 }15 int j = W;16 for (int i = n; i >= 1; i--)17 if (dp[i][j] dp[i - 1][j]) {18 printf("%d ", i);19 j -= w[i];20 }21 printf("\n");22 return 0;23}
!=: 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.Squeezed into one row: the inner loop runs backwards
Each row uses only the row above, so keep just one row dp[j] 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 if (dp[j - w[i]] + v[i] > dp[j]) dp[j] = dp[j - w[i]] + v[i];
Updating dp[j] reads dp[j − w], which should still hold the row above's value (before this item was considered). Going backwards, the boxes to the left haven't been updated for this item yet, so it reads the old value; going forwards, the box to the left has just had this item put in, and reading it means taking the same item a second time.
All three items, run both ways:
1#include <stdio.h>2 3int n = 3, W = 6;4int w[] = {0, 2, 3, 4};5int v[] = {0, 3, 4, 5};6 7int solve(int backward) {8 int dp[7] = {0};9 for (int i = 1; i <= n; i++) {10 if (backward) {11 for (int j = W; j >= w[i]; j--) // backwards: the 0-1 knapsack12 if (dp[j - w[i]] + v[i] > dp[j]) dp[j] = dp[j - w[i]] + v[i];13 } else {14 for (int j = w[i]; j <= W; j++) // forwards: one item taken many times15 if (dp[j - w[i]] + v[i] > dp[j]) dp[j] = dp[j - w[i]] + v[i];16 }17 }18 for (int j = 0; j <= W; j++) printf("%d ", dp[j]);19 printf("\n");20 return dp[W];21}22 23int main(void) {24 printf("backwards: ");25 int a = solve(1);26 printf("forwards: ");27 int b = solve(0);28 printf("backwards %d, forwards %d\n", a, b);29 return 0;30}
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: 3 books (weight 6), and we only have one. One loop's direction and the answer is wrong, with no error from compiling or running.
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's the most value?
1#include <stdio.h>2 3int main(void) {4 int w[] = {1, 3, 4, 5};5 int v[] = {1, 4, 5, 7};6 int dp[8] = {0};7 for (int i = 0; i < 4; i++)8 for (int j = 7; j >= w[i]; j--)9 if (dp[j - w[i]] + v[i] > dp[j])10 dp[j] = dp[j - w[i]] + v[i];11 printf("%d\n", dp[7]);12 return 0;13}
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 <stdio.h>2 3int main(void) {4 int w[] = {2, 3, 4};5 int v[] = {3, 4, 5};6 int dp[7] = {0};7 for (int i = 0; i < 3; i++) {8 int wi = w[i], vi = v[i];9 for (int j = )10 if (dp[j - wi] + vi > dp[j]) dp[j] = dp[j - wi] + vi;11 }12 printf("%d\n", dp[6]);13 return 0;14}
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 <stdio.h>2 3int split(int a[], int n) {4 int sum = 0;5 for (int i = 0; i < n; i++) sum += a[i];6 if (sum % 2) return 0;7 int half = sum / 2, can[1000] = {0};8 can[0] = 1;9 // for each a[i]: j from half down to a[i]; if can[j - a[i]], then can[j]10 return can[half];11}12 13int main(void) {14 int a[] = {1, 5, 11, 5};15 int b[] = {1, 2, 3, 5};16 printf("%d %d\n", split(a, 4), split(b, 4));17 return 0;18}
The complete knapsack: forwards
If there are unlimited copies of each item, take as many as you like, it's the complete knapsack. Now "the same item taken many times" is just what we want: run the inner loop forwards and change nothing else. The "wrong" forward loop in the one-row stage was in fact working out the complete knapsack's answer, 9.
| 0-1 knapsack | Complete knapsack | |
|---|---|---|
| Each item | 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 | Partition equal subset sum, target sum | Coin change (fewest coins, number of ways) |
Last lesson's "fewest coins" is a complete knapsack: any number of each coin.
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 <stdio.h>2 3int main(void) {4 int coins[] = {1, 2, 5};5 int ways[6] = {1};6 for (int i = 0; i < 3; i++)7 for (int j = coins[i]; j <= 5; j++)8 ways[j] += ways[j - coins[i]];9 printf("%d\n", ways[5]);10 return 0;11}
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
- Reading back: different from straight above means taken; take its weight off
- One row: the 0-1 knapsack's inner loop runs backwards; forwards it's the complete knapsack
1for (int i = 1; i <= n; i++)2 for (int j = W; j >= w[i]; j--)3 if (dp[j - w[i]] + v[i] > dp[j])4 dp[j] = dp[j - w[i]] + v[i];