Dynamic programming · O(nW) time and space (pseudo-polynomial)
0/1 knapsack
Fill the 2D table cell by cell, then trace back the chosen items.
The full explanation, derivation and practice are in the lesson 0/1 knapsack: a 2D table and its traceback.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
namespace Bekadan.Dsa.Examples.DynamicProgramming;
/// <summary>The best total value and the 0-based indices of the items that achieve it, ascending.</summary>
public sealed record KnapsackResult(long Best, List<int> Chosen);
/// <summary>
/// 0/1 knapsack: each item is taken whole or not at all. dp[i, w] is the best value using
/// the first i items with capacity w. Θ(n · W) time and space: pseudo-polynomial, because
/// W is a number in the input, not a count of input items.
/// </summary>
public static class Knapsack
{
public static KnapsackResult Solve(int capacity, IReadOnlyList<int> weights, IReadOnlyList<long> values)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
if (weights.Count != values.Count) throw new ArgumentException("weights and values differ in length");
int n = weights.Count;
var dp = new long[n + 1, capacity + 1]; // row 0 (no items) stays 0
for (int i = 1; i <= n; i++)
{
for (int w = 0; w <= capacity; w++)
{
if (weights[i - 1] > w)
dp[i, w] = dp[i - 1, w];
else
{
long take = dp[i - 1, w - weights[i - 1]] + values[i - 1];
dp[i, w] = Math.Max(dp[i - 1, w], take);
}
}
}
var chosen = new List<int>();
int remaining = capacity;
for (int i = n; i >= 1; i--)
{
if (dp[i, remaining] == dp[i - 1, remaining])
continue; // the best value did not need item i - 1
chosen.Add(i - 1);
remaining -= weights[i - 1];
}
chosen.Reverse();
return new KnapsackResult(dp[n, capacity], chosen);
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/DynamicProgramming/Knapsack.cs
"""0/1 knapsack: each item is taken whole or not at all.
dp[i][w] is the best value using the first i items with capacity w. Θ(n · W) time and
space: pseudo-polynomial, because W is a number in the input, not a count of input items.
"""
from collections.abc import Sequence
def knapsack(capacity: int, weights: Sequence[int], values: Sequence[int]) -> tuple[int, list[int]]:
"""Return the best total value and the 0-based indices of the chosen items, ascending."""
if capacity < 0:
raise ValueError("capacity must be non-negative")
if len(weights) != len(values):
raise ValueError("weights and values differ in length")
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)] # row 0 (no items) stays 0
for i in range(1, n + 1):
for w in range(capacity + 1):
if weights[i - 1] > w:
dp[i][w] = dp[i - 1][w]
else:
take = dp[i - 1][w - weights[i - 1]] + values[i - 1]
dp[i][w] = max(dp[i - 1][w], take)
chosen: list[int] = []
remaining = capacity
for i in range(n, 0, -1):
if dp[i][remaining] == dp[i - 1][remaining]:
continue # the best value did not need item i - 1
chosen.append(i - 1)
remaining -= weights[i - 1]
chosen.reverse()
return dp[n][capacity], chosen
Tested on CPython 3.14.0 · examples/python/dsa_examples/knapsack.py
package dev.bekadan.dsa.dp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 0/1 knapsack: each item is taken whole or not at all. dp[i][w] is the best value using
* the first i items with capacity w. Θ(n · W) time and space: pseudo-polynomial, because
* W is a number in the input, not a count of input items.
*/
public final class Knapsack {
private Knapsack() {
}
/** The best total value and the 0-based indices of the items that achieve it, ascending. */
public record Result(long best, List<Integer> chosen) {
}
public static Result solve(int capacity, int[] weights, long[] values) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity must be non-negative");
}
if (weights.length != values.length) {
throw new IllegalArgumentException("weights and values differ in length");
}
int n = weights.length;
long[][] dp = new long[n + 1][capacity + 1]; // row 0 (no items) stays 0
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
if (weights[i - 1] > w) {
dp[i][w] = dp[i - 1][w];
} else {
long take = dp[i - 1][w - weights[i - 1]] + values[i - 1];
dp[i][w] = Math.max(dp[i - 1][w], take);
}
}
}
List<Integer> chosen = new ArrayList<>();
int remaining = capacity;
for (int i = n; i >= 1; i--) {
if (dp[i][remaining] == dp[i - 1][remaining]) {
continue; // the best value did not need item i - 1
}
chosen.add(i - 1);
remaining -= weights[i - 1];
}
Collections.reverse(chosen);
return new Result(dp[n][capacity], chosen);
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/dp/Knapsack.java
#pragma once
// 0/1 knapsack: each item is taken whole or not at all. dp[i][w] is the best value using
// the first i items with capacity w. Θ(n · W) time and space: pseudo-polynomial, because
// W is a number in the input, not a count of input items.
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <span>
#include <stdexcept>
#include <vector>
namespace bekadan::dsa {
struct KnapsackResult {
std::int64_t best = 0;
std::vector<std::size_t> chosen; // 0-based item indices, ascending
};
inline KnapsackResult knapsack(std::size_t capacity, std::span<const std::size_t> weights, std::span<const std::int64_t> values) {
if (weights.size() != values.size()) throw std::invalid_argument("weights and values differ in length");
const std::size_t n = weights.size();
std::vector<std::vector<std::int64_t>> dp(n + 1, std::vector<std::int64_t>(capacity + 1, 0)); // row 0 (no items) stays 0
for (std::size_t i = 1; i <= n; ++i) {
for (std::size_t w = 0; w <= capacity; ++w) {
if (weights[i - 1] > w) {
dp[i][w] = dp[i - 1][w];
} else {
const std::int64_t take = dp[i - 1][w - weights[i - 1]] + values[i - 1];
dp[i][w] = std::max(dp[i - 1][w], take);
}
}
}
KnapsackResult result;
std::size_t remaining = capacity;
for (std::size_t i = n; i >= 1; --i) {
if (dp[i][remaining] == dp[i - 1][remaining]) continue; // the best value did not need item i - 1
result.chosen.push_back(i - 1);
remaining -= weights[i - 1];
}
std::ranges::reverse(result.chosen);
result.best = dp[n][capacity];
return result;
}
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/knapsack.hpp