How 0-1 knapsack fills a capacity row

Short answer: The 0-1 knapsack problem takes each item at most once. With capacity W and n items, the cell dp[i][w] is the best value using the first i items and capacity w. The item is skipped, or it is taken when its weight fits, and the cell is the better of those two. Rolling the items one at a time, and scanning the capacity downward, keeps the recurrence in a single array of length W+1. Time is O(nW), which is pseudo-polynomial.


What the problem actually asks

A greedy sort by value density is optimal for the fractional knapsack and not for 0-1, where an item cannot be cut. The subset structure is optimal substructure on the remaining capacity: once an item is rejected or accepted, the rest of the problem is a smaller 0-1 knapsack. That is the recurrence.

The downward scan is the implementation detail that enforces “at most once.” Scanning upward would let the same item be added again inside the same pass, which is the unbounded problem.


What the algorithm guarantees

The answer is dp[W] after every item has been considered, and it is the maximum value that fits. Time is Θ(nW). Memory is Θ(W) with the rolling array, or Θ(nW) if the decisions must be reconstructed. Reconstruction keeps a predecessor or a boolean take[i][w]. The algorithm assumes nonnegative integer weights. Real-valued weights do not index the array. Very large W makes the pseudo-polynomial bound unacceptable, and a meet-in-the-middle on n near 40, or an FPTAS, is the alternative.

The same table with a different inner loop solves unbounded knapsack. Confusing the scan direction silently solves the wrong problem and still returns a plausible number.


The working steps

  1. Allocate dp[0..W], initially 0. A capacity of 0 holds nothing, and the empty set has value 0.
  2. For each item with value v and weight w, for t from W down to w, set dp[t] = max(dp[t], dp[t−w] + v).
  3. The downward order reads dp[t−w] from before this item was considered, so the item is used at most once.
  4. After all items, dp[W] is the optimum. To list the items, either store decisions or recompute which choice matched each cell.
  5. If several items share an identity and may each be used once, they are separate iterations of the outer loop, not one iteration with a count.

O(nW) counts arithmetic on a capacity index. It is not polynomial in the bit length of W. Fractional knapsack, which may cut an item, is the density sort. Unbounded knapsack, which may repeat an item, is the upward scan. 0-1 is the downward scan.


Approaches that look simpler and fail

Approach Why it fails when the capacity loop runs upward
Scan t from w up to W while updating one item dp[t−w] may already include this item. The pass solves the unbounded problem for that item and can pack it many times.
Sort by value/weight and take items while they fit That is optimal for fractional knapsack. A 0-1 counterexample is a heavy high-value item that should displace two light ones, or the reverse.
Index the array by a real-valued weight The state is an integer capacity. Real weights need a different formulation, usually scaling or an exponential subset DP on n.
Quote O(nW) as polynomial time W can be exponential in the input length. The bound is pseudo-polynomial, which is useful and not the same claim.

Repeating items belong to the unbounded knapsack scan. Cuttable items belong to the fractional density sort. A capacity large enough to make nW impossible, with n near 40, belongs to meet-in-the-middle. 0-1 knapsack is the downward DP.


A working example

The Bash script and the Python script fill a 0-1 knapsack row from the high capacity downward, so each item is used at most once. Capacity 5, weights 2 3 4 5, values 3 4 5 6. Both print 7.

w=(2 3 4 5)
v=(3 4 5 6)
W=5
for ((c=0; c<=W; c++)); do dp[c]=0; done
n=${#w[@]}
for ((i=0; i<n; i++)); do
  for ((c=W; c>=w[i]; c--)); do
    alt=$(( dp[c-w[i]] + v[i] ))
    if (( alt > dp[c] )); then dp[c]=$alt; fi
  done
done
echo "${dp[W]}"
weights = [2, 3, 4, 5]
values = [3, 4, 5, 6]
W = 5
dp = [0] * (W + 1)
for w, v in zip(weights, values):
    for cap in range(W, w - 1, -1):
        dp[cap] = max(dp[cap], dp[cap - w] + v)
best = 0
items = list(zip(weights, values))

def brute(i, cap):
    global best
    if i == len(items):
        return 0
    skip = brute(i + 1, cap)
    w, v = items[i]
    take = 0 if w > cap else v + brute(i + 1, cap - w)
    return max(skip, take)

assert dp[W] == brute(0, W) == 7
print(dp[W])

Where it is used

The 0-1 knapsack recurrence is the capital-budget and cargo-loading problem: each item is taken once, and the capacity row stores the best value. The unbounded coin-change recurrence is the sibling that allows repeats. Cryptographic key search is a different algorithm.


When you can drop this algorithm

Drop the DP when W is huge and n is the smaller parameter. Use meet-in-the-middle or an approximation scheme. Keep the downward row when weights are integers, each item may be taken once, and nW fits.


Why this stays published

We publish this so a search for 0-1 knapsack returns the downward capacity scan that keeps each item from being reused. 0-1 knapsack fills a capacity array from the top downward, in O(nW) time, so each item is considered at most once.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *