Quick Answer
Knapsack problem fills a bag with the most value. This post solves the 0/1 knapsack with a DP table. Items are taken in full or not at all. Dynamic programming stores the top value for every weight limit. Time is O(n times W) and space is O(n times W). Space drops to O(W) with a single row. Python and C++ code below was executed.
Knapsack problem questions are where most students meet dynamic programming for the first time. Many of them panic there. Code fills a table and nobody explains what the table means.
Every cell in that table answers one small question. Once you see it the table stops being scary. Sections below trace the table by hand and give 3 approaches with tested code.
What Is the Knapsack Problem?
Knapsack problem gives you a bag with a weight limit. Every item has a weight and a value. Choose items that fit in the bag and give the most total value.
This post explains the 0/1 knapsack. Here 0/1 means an item is taken in full or not at all. Half an item is not allowed and that single rule makes the knapsack problem interesting.
Knapsack problem is a standard dynamic programming exercise. Review how recursion works first because dynamic programming grows out of recursion.
What Is the One Choice Behind the Knapsack Problem?
Every item gives you two options. Take it or do not take it.
Without the item your top value is what earlier items already give. With the item you gain its value but use up weight so less room remains. Dynamic programming tries both options and stores the larger value.
How Does the Knapsack Problem DP Table Work Step by Step?
Take a bag with weight limit 5 and 3 items. Item 1 weighs 2 and is worth 3.
Item 2 weighs 3 and is worth 4. Item 3 weighs 4 and is worth 5.
Step #1: Set Up the Table
What you get. Grid with one row per item count and one column per weight limit from 0 to 5. Row 0 and column 0 start at 0 because no items or no room means no value.
Step #2: Fill Every Cell
What you get. Best value for that item count and weight limit. Every cell compares 2 numbers. One is the cell directly above and the other is the item value plus a cell in the row above.
| Items used | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| None | 0 | 0 | 0 | 0 | 0 | 0 |
| Item 1 (weight 2, value 3) | 0 | 0 | 3 | 3 | 3 | 3 |
| Items 1 and 2 (weight 3, value 4) | 0 | 0 | 3 | 4 | 4 | 7 |
| Items 1, 2 and 3 (weight 4, value 5) | 0 | 0 | 3 | 4 | 5 | 7 |
Look at items 1 and 2 with weight limit 5. Not taking item 2 gives 3 from the cell above.
Taking item 2 gives its value 4 plus 3 from the weight limit 2 cell in the row above. Seven beats 3 so the cell stores 7.
Step #3: Take the Answer From the Last Cell
What you get. Final answer of the knapsack problem. Bottom right cell is 7 so items 1 and 2 give the highest value. Their weights 2 and 3 fill the bag exactly.
Table stores answers to smaller problems so no problem is solved twice. Every cell reuses cells from the row above. Small answers come first and build the large one.
How Do You Code the Knapsack Problem in Python and C++?
Code is the table written as 2 loops. Outer loop walks items and inner loop walks weight limits.
Approach #1: Full Table
What you get. Entire table so you can trace items later. Python version first.
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
dp[i][w] = dp[i - 1][w]
if weights[i - 1] <= w:
take = values[i - 1] + dp[i - 1][w - weights[i - 1]]
dp[i][w] = max(dp[i][w], take)
return dp
weights = [2, 3, 4]
values = [3, 4, 5]
table = knapsack(weights, values, 5)
for row in table:
print(row)
print(table[3][5])
Line with max is the take or not take choice. Output is the 4 table rows from above and then 7.
C++ version follows.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int knapsack(const vector<int>& weights, const vector<int>& values, int capacity) {
int n = weights.size();
vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0));
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
dp[i][w] = dp[i - 1][w];
if (weights[i - 1] <= w) {
int take = values[i - 1] + dp[i - 1][w - weights[i - 1]];
dp[i][w] = max(dp[i][w], take);
}
}
}
return dp[n][capacity];
}
int main() {
cout << knapsack({2, 3, 4}, {3, 4, 5}, 5) << endl;
cout << knapsack({2, 3, 4}, {3, 4, 5}, 6) << endl;
}
It returns 7 for weight limit 5 and 8 for weight limit 6. Code uses vector because variable length arrays are not standard C++.
Approach #2: Single Row
What you get. Space of O(W) in place of O(n times W). Row is updated from right to left so every item is used once.
def knapsack_row(weights, values, capacity):
dp = [0] * (capacity + 1)
for weight, value in zip(weights, values):
for w in range(capacity, weight - 1, -1):
dp[w] = max(dp[w], value + dp[w - weight])
return dp[capacity]
print(knapsack_row([2, 3, 4], [3, 4, 5], 5))
print(knapsack_row([2, 3, 4], [3, 4, 5], 6))
Output is 7 and 8. Forward loops give 9 for weight limit 6 because item 1 gets used 3 times.
Approach #3: Trace Back the Items
What you get. List of chosen items and not just the value. Start at the last cell and compare it with the cell above.
from kn_code import knapsack
def chosen_items(weights, values, capacity):
dp = knapsack(weights, values, capacity)
items, w = [], capacity
for i in range(len(weights), 0, -1):
if dp[i][w] != dp[i - 1][w]:
items.append(i)
w -= weights[i - 1]
return items[::-1]
print(chosen_items([2, 3, 4], [3, 4, 5], 5))
print(chosen_items([2, 3, 4], [3, 4, 5], 6))
Different values mean the item was taken. Output is [1, 2] for weight limit 5 and [1, 3] for weight limit 6.
Tested. Python 3.13.18 matched a brute force check of all item subsets on 1,000 random cases for the table version and the single row version.
g++ 13.3 compiled the C++ version with warnings on. Tests ran in a cloud sandbox.
What Is the Time and Space Complexity of the Knapsack Problem?
Time is O(n times W) where n is the item count and W is the weight limit. One cell is filled for every item and every weight limit. Space is O(n times W) for the table and O(W) for a single row.
W is the size of the limit and not the item count. Huge limits mean a huge table even with few items. Knapsack problem time is called pseudo polynomial for this reason.
Test below used 20 items with the single row version. Table lists the lowest of 3 trials in CPython 3.13.18.
| Weight limit W | Time for 20 items |
|---|---|
| 1,000 | 0.0009 s |
| 100,000 | 0.109 s |
| 1,000,000 | 1.096 s |
Time grows with W as the formula says. Brute force over all subsets of 20 items took 0.879 s with W of 500 while the table took 0.001 s.
See time complexity for the notation.
How Does 0/1 Knapsack Compare With Fractional Knapsack?
Fractional knapsack takes a piece of an item like half a bag of rice. Greedy choice works there. Dynamic programming handles the 0/1 version.
| Point | 0/1 knapsack | Fractional knapsack |
|---|---|---|
| Item rule | Full item or none | Pieces accepted |
| Method | Dynamic programming | Greedy by value per weight |
| Answer for items above and weight limit 6 | 8 | 8.25 |
| Time | O(n times W) | O(n log n) for sorting |
Fractional answer is 8.25 because items 1 and 2 give 7 at weight 5. One quarter of item 3 adds 1.25. Full items only reach 8.
Practice the pattern in the dynamic programming practice set and open the 0/1 knapsack visualiser to watch cells fill.
Wider topic is in the dynamic programming lesson and the dynamic programming guide.
Frequently Asked Questions
What Is the 0/1 Knapsack Problem?
It is a knapsack problem where you fill a bag with a weight limit for the most value. Every item is taken in full or not at all. Dynamic programming solves it.
Why Use Dynamic Programming for the Knapsack Problem?
Same smaller problems appear again and again. Tables store those answers so every one is solved once and repeated work disappears.
Is the Knapsack Problem Solved in Polynomial Time?
No. Time is O(n times W) which is pseudo polynomial because it depends on the size of W and not only the item count.
What Is the Difference Between 0/1 and Fractional Knapsack?
Full items need dynamic programming. Fractional knapsack accepts pieces and a greedy choice by value per weight solves it.
Can Recursion Alone Solve the 0/1 Knapsack?
Yes. Plain recursion repeats the same work and slows down. Storing results in a table converts it into dynamic programming.
How Do You Find the Items Chosen and Not Just the Value?
Start at the last cell and move back. Cells that differ from the cell above mean the item was taken. Subtract its weight and continue upward.
Why Does the Single Row Loop Go Backward?
Forward loops reuse an item inside the same pass. With weight limit 6 a forward loop gave 9 in testing while the correct answer is 8.
What Should You Remember About the 0/1 Knapsack?
One question repeats for every item and weight limit. Take the item or do not take it and store the larger value.
Key takeaways.
- Knapsack problem time is O(n times W) and space drops to O(W) with a single row.
- Last cell is the answer and a trace back gives the items.
- Fractional knapsack is greedy and 0/1 knapsack needs a table.
Check yourself. With weight limit 6 and the same 3 items what lands in the last cell? Answer is 8 from items 1 and 3.