Sub topic 11
An FPTAS for 0/1 Knapsack
This chapter assumes you know the PTAS and FPTAS definitions from the previous chapter. It also assumes you can read a one-dimensional dynamic program (DP) in Python and that you are comfortable with floor rounding and big-O bounds. The goal is to turn an exact but pseudo-polynomial knapsack algorithm into one that runs in time polynomial in both n and 1/ε, while losing at most an ε fraction of the optimal value.
The Problem and Why the Exact DP Is Not Enough
In 0/1 knapsack you have n items. Item i has a positive value vi and a non-negative weight wi. You also have a capacity W. The task is to choose a subset of items with total weight at most W and the largest possible total value. The decision version is NP-complete.
There are two standard exact DPs:
| DP indexed by | Table entry | Running time | Polynomial? |
|---|---|---|---|
| Weight | best value using weight ≤ c | O(nW) | No: W can be exponential in its bit length |
| Value | least weight that reaches value exactly p | O(nV), V = Σ v_i | No: V can be exponential in its bit length |
Both are pseudo-polynomial. Their running time is polynomial in the magnitude of the numbers, but the input encodes those numbers in only O(log W) or O(log V) bits. The value-indexed DP is the one to approximate. If you make the values small, the table becomes small, and you can make values small by rounding them.
The Idea: Scale Values, Keep Weights Exact
Pick a scaling factor K and replace each value by v'i = ⌊vi / K⌋. Weights are never rounded, so every subset the DP calls feasible really is feasible. Rounding changes only how the DP ranks feasible subsets.
Choose K = ε · vmax / n, where vmax is the largest item value. Two things follow from this choice:
- Each scaled value is at most v_max / K = n/ε, so the total scaled value is at most n²/ε. The DP table has polynomial size.
- Each item loses less than K in value through rounding. Any subset has at most n items, so it loses less than nK = ε · vmax in total, and vmax is at most OPT.
The Algorithm
The core routine below is a standard value-indexed DP over scaled profits. min_w[p] holds the least weight of any subset with scaled profit exactly p. keep[i][p] records whether item i improved that entry when it was processed, which is enough to reconstruct the chosen set. The wrapper handles an edge case that the core routine ignores. That edge case is explained in the gotchas section.
def knapsack_fptas(values, weights, capacity, eps):
n = len(values)
k = eps * max(values) / n
scaled = [int(v // k) for v in values]
total = sum(scaled)
INF = float("inf")
min_w = [0] + [INF] * total
keep = [[False] * (total + 1) for _ in range(n)]
for i in range(n):
for p in range(total, scaled[i] - 1, -1):
cand = min_w[p - scaled[i]] + weights[i]
if cand < min_w[p]:
min_w[p] = cand
keep[i][p] = True
best = max(p for p in range(total + 1) if min_w[p] <= capacity)
items, p = [], best
for i in range(n - 1, -1, -1):
if keep[i][p]:
items.append(i)
p -= scaled[i]
return sorted(items)
def knapsack_fptas_safe(values, weights, capacity, eps):
# Keep only items that can be chosen at all, so that v_max <= OPT holds.
idx = [i for i in range(len(values))
if weights[i] <= capacity and values[i] > 0]
if not idx:
return []
sub = knapsack_fptas([values[i] for i in idx],
[weights[i] for i in idx], capacity, eps)
return [idx[j] for j in sub]
print(knapsack_fptas([60, 100, 120], [10, 20, 30], 50, 0.1))
print(knapsack_fptas_safe([60, 100, 120, 1000], [10, 20, 30, 99], 50, 0.1))Both calls print [1, 2]. In the first call, K = 0.1 · 120 / 3 = 4 and the scaled values are 15, 25, and 30. The best feasible scaled profit is 55, reached by items 1 and 2 with weight 50 and true value 220, which is optimal here. In the second call, the wrapper drops item 3 before scaling because it can never fit.
The inner loop runs p downward so that each item is used at most once. That is the 0/1 constraint. If you run p upward, you get unbounded knapsack instead.
Proof of the (1 − ε) Guarantee
Let S* be an optimal subset with value OPT, and let S be the subset the algorithm returns. Write v'(T) for the scaled value of a set T.
- Rounding loses less than K per item: K · v'i ≥ vi − K.
- The DP is exact on scaled values, and S is feasible, so v'(S) ≥ v'(S).
- Rounding only goes down, so v(S) ≥ K · v'(S).
Chaining these:
v(S) ≥ K · v'(S) ≥ K · v'(S) ≥ Σ_{i∈S} (vi − K) ≥ OPT − nK = OPT − ε · vmax.
After filtering, the most valuable item fits on its own, so OPT ≥ v_max. Therefore v(S) ≥ OPT − ε · OPT = (1 − ε) · OPT.
Running Time and Space
The total scaled value is at most n · (n/ε) = n²/ε. The DP does n passes over that range, so it runs in O(n³/ε) time. That is polynomial in n and in 1/ε, which is what makes this an FPTAS and not just a PTAS.
| ε | K (with v_max = 10⁶, n = 100) | Max scaled total | DP cells (≈ n · total) |
|---|---|---|---|
| 0.5 | 5,000 | 20,000 | 2 × 10⁶ |
| 0.1 | 1,000 | 100,000 | 10⁷ |
| 0.01 | 100 | 1,000,000 | 10⁸ |
Halving ε doubles the work. Under a PTAS with a running time like n^(1/ε), the same change would square it.
You can get a sharper bound by using the actual total of the scaled values in place of n²/ε. The code already does this by sizing the table with sum(scaled).
Gotchas and Failure Modes
An item that cannot fit breaks the bound
The proof uses OPT ≥ vmax. If the most valuable item weighs more than W, that inequality can fail badly. K then becomes large, every other item rounds down to 0 or 1, and the DP can no longer tell good subsets from bad ones. The guarantee holds only after you remove items with wi > W, which is what knapsack_fptas_safe does.
Memory, not time, is often the real limit
The keep table has n · (total + 1) booleans, which is O(n³/ε) in the worst case. With n = 1000 and ε = 0.01, that is about 10¹¹ entries. You have three options:
- Store a parent pointer per profit along with the set of items, which is cheaper when solutions are small.
- Recompute the solution with a divide-and-conquer reconstruction in the style of Hirschberg's algorithm, which keeps O(n²/ε) space.
- Settle for the optimal value only, which needs just the one-dimensional
min_warray.
Floating-point scaling
K is a float, so v // k can land one unit off when v/K is very close to an integer. This does no harm to correctness. Being off by one is still an error below K + (a tiny amount), and the proof has slack. If you want exact arithmetic, use the integer formula ⌊vi · n / (ε · vmax)⌋ with ε given as a fraction.
Zero-value items and ε ≥ 1
Items with v_i = 0 never help, so the wrapper drops them. If every value is 0, the function returns []. For ε ≥ 1 the guarantee (1 − ε) · OPT ≤ 0 is empty, so taking any single item that fits already satisfies it.
Why this does not work for every problem
Scaling succeeds here because knapsack has a pseudo-polynomial exact algorithm that depends only on the magnitude of the values. Strongly NP-hard problems, such as bin packing or the multi-dimensional knapsack, stay NP-hard even when the numbers are polynomially bounded. They have no FPTAS unless P = NP. The approximation classes chapter makes this precise.
Decision Criteria
- Need a certified near-optimum with small n and huge values: use the FPTAS.
- Weights are small integers: the exact O(nW) DP is often faster and gives the optimum.
- Need only a 1/2-approximation, fast: take the better of the greedy-by-ratio solution and the single most valuable item. This takes O(n log n) time.
- Large practical instances: branch-and-bound or a MIP solver usually finds the exact optimum quickly. The FPTAS gives you a worst-case guarantee, which those solvers do not.
Exercise
Suppose you change the scaling factor to K = ε · v_max / (2n). What happens to the approximation guarantee and to the running time?
Show answer
The total rounding loss becomes less than nK = ε · v_max / 2, so the output has value at least (1 − ε/2) · OPT. The guarantee improves. The total scaled value becomes at most 2n²/ε, so the running time doubles, which is still O(n³/ε).
Exercise
Give an instance where running knapsack_fptas without the filtering wrapper, with ε = 0.5, returns a solution worse than (1 − ε) · OPT.
Show answer
Use values [1000, 3, 2, 2], weights [100, 1, 1, 1], and capacity 2. Then OPT = 5 (items 1 and 2). Without filtering, K = 0.5 · 1000 / 4 = 125, so items 1, 2, and 3 all scale to 0. Every feasible subset then has scaled profit 0, the DP keeps the empty set as the cheapest way to reach profit 0, and the function returns [] with value 0, which is less than 0.5 · 5. With filtering, item 0 is removed and K = 0.5 · 3 / 3 = 0.5, so the scaled values become 6, 4, and 4. The DP then finds items 1 and 2, with value 5.
Exercise
Why must the inner DP loop iterate p from high to low, and what problem would it solve if it iterated from low to high?
Show answer
Iterating downward means minw[p − scaled[i]] still holds the value from before item i was considered, so item i is used at most once. Iterating upward lets minw[p − scaled[i]] already include item i, so the item can be added many times. That solves unbounded knapsack instead of 0/1 knapsack.