Algorithm · Dynamic programming · O(nW) time and space (pseudo-polynomial)
0/1 knapsack
Pick items of given weights and values to maximize value within a capacity, each item at most once. A 2D table in O(nW) pseudo-polynomial time.
The full derivation, edge cases and exercises are in the lesson 0/1 knapsack: a 2D table and its traceback. Open it full width in the playground.
On this page
The idea
best[i][w] is the best value using the first i items with capacity w. Item i is either skipped (best[i − 1][w]) or taken if it fits (value + best[i − 1][w − weight]). Filling the table row by row and tracing back from the last cell recovers the chosen items.
O(nW) looks polynomial but grows with the numeric capacity, not its number of digits: the problem is NP-hard in general.
Steps
- Row 0 (no items) is all zeros.
- For each item and each capacity, take the better of skip and take.
- Trace back: where a cell differs from the one above, the item was taken.
Invariants
What holds at every step; the correctness argument rests on these.
- best[i][w] is optimal for items 1 … i and capacity w.
- Each row depends only on the row above.
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| 2D table | O(nW) | O(nW) | |
| One row, capacities right to left | O(nW) | O(W) | Loses the trace-back. |
When to use it
Use it when
- Budgeted selection with integer weights and a modest capacity.
Avoid it when
- Items can be split (fractional knapsack: greedy by value per weight is optimal).
- Capacity is huge: the table is too large.
Step through it
The interactive lab for 0/1 knapsack: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
The table and traceback in four languages, each checked against one shared fixture that fixes both the best value and the chosen items (no items, zero capacity, nothing fits, ties, exact fill, large values) and 1,000 random inputs of up to ten items compared with a brute force over all subsets, also checking that the chosen items fit and add up to the best value.
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
Learn more
Lessons
- 0/1 knapsack: a 2D table and its traceback· M32 Dynamic Programming
Data structures it uses
Problems, patterns and exercises
- PatternDynamic programming (1D and 2D)· O(states × transitions)
- Complexity exerciseFilling an n × n table· Θ(n²)