M32 · Dynamic Programming

0/1 Knapsack: Filling a 2D Table and Tracing Back the Choice

Given items with weights and values and a capacity, choose the items with the largest total value that fit. Trying every subset costs 2ⁿ. A table dp[i][w], the best value using the first i items with capacity w, answers the question in n·W steps, and walking back through the table recovers which items to take.

~45 minAdvancedC# · Python · Java · C++
Curriculum: M32 Dynamic Programming · 2 of 2 lessons available

You will be able to

  • Define the state dp[i][w] and derive the take-or-skip recurrence for the 0/1 knapsack.
  • Fill the table row by row and explain which cells each entry depends on.
  • Recover the chosen items by tracing back from dp[n][W].
  • Explain why Θ(n·W) is pseudo-polynomial and when the table is too large to use.
  • Reduce the memory to one row of W + 1 entries, and explain why the inner loop must then run backwards.

Helpful before this lesson

  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.
  • M31 Backtracking — Choose, explore, undo: searching decision trees with pruning.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

The problem

You have n items; item k has an integer weight wₖ and a value vₖ. A knapsack holds total weight at most W. Choose a set of items, each taken whole or not at all (that is the "0/1"), to maximise the total value. With capacity 7 and items (weight 1, value 1), (3, 4), (4, 5), (5, 6), the best choice is the second and third items: weight 7, value 9.

Simple rules fail. Taking the most valuable item first gives (5, 6), then only (1, 1) still fits: value 7. Taking the best value per unit of weight first fails too: try the Best ratio is not best preset. Trying every subset works but costs 2ⁿ. Dynamic programming gets the exact optimum by organising the subsets so that shared work is done once.

The state and the recurrence

Decide the items one at a time, as in the subset search of the backtracking lesson. After deciding the first i items, all that matters for the future is how much capacity is left, not which items used it. So define:

dp[i][w] = the best total value achievable with the first i items and capacity w.

For item i (weight wᵢ, value vᵢ) there are two cases:

  • Skip it: the best is whatever the first i − 1 items achieve with the same capacity, dp[i − 1][w].
  • Take it (only if wᵢ ≤ w): it uses wᵢ of the capacity, so the rest comes from dp[i − 1][w − wᵢ], plus vᵢ.
dp[0][w] = 0                                            (no items)
dp[i][w] = dp[i−1][w]                                   if wᵢ > w
dp[i][w] = max(dp[i−1][w], dp[i−1][w − wᵢ] + vᵢ)        otherwise

The answer is dp[n][W]. Both cases look only at row i − 1, so filling the table row by row, left to right, always has the needed entries ready. In the lab, the cell being filled is highlighted, the "skip" source (straight above) and the "take" source (above and wᵢ to the left) are marked, and the explanation shows both candidates before the larger one is stored.

Tracing back the chosen items

The table stores values, not decisions, but the decisions can be read back. Start at dp[n][W] and walk up one row at a time:

  • If dp[i][w] equals dp[i − 1][w], item i was not needed: move up.
  • Otherwise item i was taken: record it and move up to row i − 1 at column w − wᵢ.

When row 0 is reached, the recorded items are an optimal set. When both choices give the same value, this rule leaves the item out, so ties are broken towards earlier items; another tie rule can return a different set with the same total. The lab draws the traceback as a path through the table, and the shared fixture pins down which set this rule returns.

Cost: Θ(n·W), and why that is pseudo-polynomial

There are (n + 1)(W + 1) entries and each costs O(1), so time and memory are Θ(n·W). That looks polynomial, but it is polynomial in the value of W, not in the size of the input. W is written with about log₂ W bits, so adding ten bits to the capacity multiplies the table by about 1,000 while the input barely grows. An algorithm that is polynomial in the numeric values of the input but not in its length is called pseudo-polynomial.

In practice: the table method is excellent for capacities in the thousands or millions and useless for W = 10¹⁵. That is consistent with the 0/1 knapsack being NP-hard in general: nobody knows an algorithm polynomial in n and log W. With huge capacities but few items, a different state (for example the minimum weight for each total value, when values are small) or a search with pruning may be the better choice.

One row is enough

Row i only reads row i − 1, so you can keep a single array best[0..W] and update it in place, iterating w downwards:

for each item (weight, value):
    for w from W down to weight:
        best[w] = max(best[w], best[w − weight] + value)

Going down, best[w − weight] still holds the previous row's value when it is read. Going up, it might already include the current item, which would let the item be taken twice: that is the recurrence for the unbounded knapsack, where each item may be used any number of times. The one-row version needs Θ(W) memory but loses the information the traceback needs; keep the full table (as the teaching implementation does) if you must report the chosen items.

Language notes

  • C#: a rectangular array new long[n + 1, capacity + 1] is zero-initialised: row 0 is ready.
  • Python: build rows with a comprehension, [[0] * (W + 1) for _ in range(n + 1)]; [[0] * (W + 1)] * (n + 1) would make every row the same list.
  • Java: new long[n + 1][capacity + 1] is zero-initialised; the result is a record.
  • C++: std::vector<std::vector<std::int64_t>>, or one flat vector indexed i * (W + 1) + w for better locality. The traceback loop runs i from n down to 1 with an unsigned index, which stops correctly because the condition i >= 1 is checked before i could wrap.

Values are summed in 64-bit integers in C#, Java and C++ (Python integers do not overflow); with values up to 10⁹ and a few thousand items, 32 bits would not be enough.

The teaching implementation

All four languages fill the same table with the same anchored lines as the lab and return the best value plus the chosen indices in ascending order. They read one shared fixture that fixes both the value and the chosen set (no items, zero capacity, nothing fits, ties, exact fill, large values) and compare 1,000 random inputs of up to ten items with a brute force over all 2ⁿ subsets, also checking that the chosen items fit and add up to the reported value.

Common mistakes

  • Greedy by value or by value per weight. Optimal for the fractional knapsack (where items can be split), not for 0/1.
  • Reading dp[i][w − wᵢ] instead of dp[i − 1][w − wᵢ]: that silently solves the unbounded knapsack.
  • One-row version with w going upwards: the same bug in disguise.
  • Index off by one between items and rows: row i describes item i − 1 in 0-based arrays.
  • Forgetting the wᵢ > w case and indexing a negative column.

Edge cases

  • No items or W = 0: the answer is 0 with no items chosen.
  • Items heavier than W: their rows copy the row above (the Nothing fits preset).
  • Items with value 0: never needed; the traceback leaves them out.

Worked practice

1. Fill the last row by hand: capacity 4, items (2, 3), (2, 3), (4, 6). What is dp[3][4], and which items does the traceback choose?

Answer

dp[3][4] = 6. Both "the two 2s" (3 + 3) and "the 4" (6) give 6; at row 3, dp[3][4] = 6 equals dp[2][4] = 6, so item 3 is skipped and the traceback takes items 1 and 2.

2. The table for n = 100 items and W = 10⁶ has how many entries? Is that practical?

Answer

101 × 1,000,001 ≈ 10⁸ entries: about 800 MB as 64-bit integers, too much for a full table. The one-row version needs about 8 MB and 10⁸ simple steps, which is practical if you only need the value.

3. Why does the traceback compare dp[i][w] with dp[i − 1][w] rather than recompute both candidates?

Answer

If the values are equal, skipping item i already achieves the optimum, so there is an optimal set without it. If they differ, dp[i][w] must have come from the "take" case. One comparison per row is enough, so the traceback is O(n).

Summary

  • State dp[i][w]: best value with the first i items and capacity w; take-or-skip recurrence.
  • Fill row by row; the answer is dp[n][W]; trace back by comparing each cell with the one above.
  • Θ(n·W) time and memory: pseudo-polynomial, because W is a number, not an input length.
  • One row of W + 1 entries suffices if you iterate w downwards and do not need the items.

Full implementation

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

References