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

Edge cases to test

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