Algo-Sim › Dynamic Programming
0/1 Knapsack
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Choose items (each at most once) to maximise total value without exceeding the weight capacity W.
Problem
Item i weighs weights[i] and is worth values[i]. Choose a set of items, each at most once, whose total weight is at most the capacity W, so that their total value is as large as possible. Return that value.
Constraints
- 1 ≤ n ≤ 1000 items
- 1 ≤ W ≤ 1000
- Weights and values are positive integers
- Pseudo-polynomial: O(n·W) time
Edge cases to test
- Capacity 0
- An item heavier than the capacity
- All items fit
Follow-up questions
- Why is it called pseudo-polynomial?
- O(n·W) depends on the value of W, not its number of bits; W = 10⁹ makes the table impossible.
- What if W is huge but values are small?
- Flip the DP: the least weight needed for each total value, O(n·Σvalue).
- What if items can be reused?
- Loop capacities upward (the unbounded knapsack): the same O(n·W).
Solution
Java
public int knapsack(int[] weights, int[] values, int W) {
int n = weights.length;
int[][] dp = new int[n + 1][W + 1];
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
dp[i][w] = dp[i - 1][w];
if (weights[i - 1] <= w) {
dp[i][w] = Math.max(dp[i][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
}
}
}
return dp[n][W];
}Python
def knapsack(weights, values, W):
n = len(weights)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(W + 1):
dp[i][w] = dp[i - 1][w]
if weights[i - 1] <= w:
dp[i][w] = max(dp[i][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
return dp[n][W]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int knapsack(vector<int> &weights, vector<int> &values, int W) {
int n = int(weights.size());
vector<vector<int>> dp = vector<vector<int>>(n + 1, vector<int>(W + 1));
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
dp[i][w] = dp[i - 1][w];
if (weights[i - 1] <= w) {
dp[i][w] = std::max(dp[i][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
}
}
}
return dp[n][W];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)