Sub topic 16
Approximating Within a Factor: The Knapsack FPTAS
This chapter assumes you know the value-indexed DP from the earlier chapter: dp[t] holds the minimum weight needed to reach a total value of exactly t. It also assumes you can reconstruct chosen items from a 2D table and that you know why 0/1 knapsack is NP-hard.
The value-indexed DP runs in O(n · V), where V is the sum of all values. That is fast when values are small integers. When values are in the millions, or are prices with many significant digits, V gets too large and the table no longer fits in time or memory. The fix is to give up a controlled amount of accuracy. You round the values down to a coarse scale so that V becomes small, solve the rounded problem exactly, and prove that the answer is close to optimal.
What "approximation scheme" means
An algorithm is a (1 − ε)-approximation for a maximization problem if it always returns a feasible solution with value at least (1 − ε) · OPT, where OPT is the optimal value.
An approximation scheme takes ε as an input, so you choose how much quality you are willing to trade for speed. There are two kinds:
| Kind | Running time requirement | Example of an allowed bound |
|---|---|---|
| PTAS | Polynomial in n for each fixed ε | O(n^(1/ε)) |
| FPTAS | Polynomial in both n and 1/ε | O(n³/ε) |
A PTAS can become impractical as ε shrinks, because 1/ε can sit in the exponent. An FPTAS cannot. Knapsack has an FPTAS, and it is the textbook example of one.
The scaling idea
Choose a scale factor K and replace every value vᵢ with a rounded value:
v′ᵢ = ⌊vᵢ / K⌋
Then run the exact value-indexed DP on the rounded values v′ᵢ with the original weights and capacity. The weights are never touched, so any set that the DP picks is feasible for the real problem.
The scale factor used is:
K = ε · v_max / n
Here vmax is the largest value among items that fit in the knapsack on their own. With this K, each rounded value is at most vmax / K = n / ε, so the rounded total is at most n²/ε. The DP table has n rows and at most n²/ε + 1 columns, which gives O(n³/ε) time. That bound does not depend on the size of the values at all.
Why the answer is within (1 − ε) of optimal
Let S* be an optimal set and S be the set the algorithm returns. Rounding loses less than K per item, so for any item:
K · v′ᵢ ≤ vᵢ < K · v′ᵢ + K
The argument then runs in four steps.
- Rounding only lowers values, so the true value of S is at least K times its rounded value: v(S) ≥ K · v′(S).
- S is optimal for the rounded problem, and S is feasible there too, so v′(S) ≥ v′(S).
- S has at most n items, and each loses less than K, so K · v′(S) > v(S*) − nK = OPT − ε · v_max.
- Every item in the filtered list fits alone, so OPT ≥ vmax, and therefore ε · vmax ≤ ε · OPT.
Chaining these gives v(S) ≥ OPT − ε · OPT = (1 − ε) · OPT.
Implementation
The code below uses Fraction for K so that rounding is exact. With floats, 100 / (0.5 * 100 / 3) evaluates to slightly less than 6, the floor becomes 5, and the analysis stops matching the code. If K comes out below 1, the code clamps it to 1. With integer values, K = 1 means no rounding at all, so the result is exact and still fast enough.
from fractions import Fraction
def value_dp_choose(values, weights, capacity):
# Exact value-indexed DP with reconstruction.
# dp[i][t] = min weight using the first i items to reach value exactly t.
n = len(values)
total = sum(values)
INF = float('inf')
dp = [[INF] * (total + 1) for _ in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
v, w = values[i - 1], weights[i - 1]
for t in range(total + 1):
dp[i][t] = dp[i - 1][t]
if t >= v and dp[i - 1][t - v] + w < dp[i][t]:
dp[i][t] = dp[i - 1][t - v] + w
best = max(t for t in range(total + 1) if dp[n][t] <= capacity)
chosen = []
t = best
for i in range(n, 0, -1):
if dp[i][t] != dp[i - 1][t]:
chosen.append(i - 1)
t -= values[i - 1]
chosen.reverse()
return chosen
def knapsack_fptas(values, weights, capacity, eps):
# Returns (true value, chosen original indices) with value >= (1 - eps) * OPT.
fit = [i for i in range(len(values)) if weights[i] <= capacity]
if not fit:
return 0, []
v_max = max(values[i] for i in fit)
K = max(Fraction(str(eps)) * v_max / len(fit), Fraction(1))
scaled = [int(values[i] // K) for i in fit]
picked = value_dp_choose(scaled, [weights[i] for i in fit], capacity)
chosen = [fit[j] for j in picked]
return sum(values[i] for i in chosen), chosen
print(knapsack_fptas([60, 100, 120], [10, 20, 30], 50, 0.5)) # (220, [1, 2])
print(knapsack_fptas([100, 51, 51], [10, 5, 5], 10, 0.5)) # (100, [0])In the first call, K = 20 and the rounded values are 3, 5 and 6. Rounding keeps the ranking intact, and the algorithm finds the true optimum of 220.
The second call shows how rounding can lose value. The optimum takes items 1 and 2 for 102. With K = 50/3, the rounded values are 6, 3 and 3. Item 51 rounds down from 3.06 to 3, so {0} and {1, 2} both score 6 after rounding, and the DP keeps {0}. The returned value of 100 is below optimal, but it is well above the guaranteed (1 − 0.5) · 102 = 51.
How ε controls cost
For n = 100 items, the rounded total is at most n²/ε, so each row of the table has about that many columns:
| ε | Max rounded total (n²/ε) | Table cells (about n³/ε) | Guarantee |
|---|---|---|---|
| 0.5 | 20,000 | 2 million | ≥ 50% of OPT |
| 0.1 | 100,000 | 10 million | ≥ 90% of OPT |
| 0.01 | 1,000,000 | 100 million | ≥ 99% of OPT |
Each tenfold reduction in ε costs about ten times more work. That linear relationship is the "fully polynomial" part. In practice the observed error is usually far smaller than ε, because rounding errors across items partly cancel and the worst case needs every item in S* to lose almost K.
Refinements and gotchas
A tighter lower bound
Replacing v_max with a better lower bound L on OPT increases K and shrinks the table. A cheap choice is L = max(greedy-by-ratio value, best single item). L is at least OPT/2, and since L ≤ OPT, using K = ε · L / n keeps the proof valid. The rounded total of any feasible set is then at most OPT/K ≤ 2n/ε. You can cap the DP columns there and get O(n²/ε) time.
Memory
The 2D table needed for reconstruction has O(n³/ε) cells in the basic version. If you only need the value, the one-array version from earlier chapters uses O(n²/ε) memory. To get the items as well without the full table, store a parent pointer per cell or use a divide-and-conquer reconstruction.
Report the true value
Report the sum of the original values of the chosen items, never K times the rounded total. The rounded total underestimates the true value.
Where this does not carry over
The scheme works because knapsack is only weakly NP-hard: it is hard only when its numbers are large. Strongly NP-hard problems have no FPTAS unless P = NP. Even the two-constraint knapsack from the next chapter has no FPTAS unless P = NP, although it does have a PTAS.
When to use it
Use the FPTAS when values are large or non-integer, the capacity is also too large for weight-indexed DP, n is in the hundreds or more, and a certified near-optimal answer is acceptable. If you need the exact optimum, branch and bound or integer programming solvers are usually faster in practice on typical instances, but they give no polynomial guarantee.
Exercise
With n = 4 items, ε = 0.25 and v_max = 800, what is K, what is the largest possible rounded value of a single item, and what is the worst-case absolute loss bound nK?
Show answer
K = 0.25 · 800 / 4 = 50. The largest rounded value is ⌊800 / 50⌋ = 16, which equals n/ε. The loss bound is nK = 4 · 50 = 200 = ε · v_max, so the result is at least OPT − 200 ≥ 0.75 · OPT.
Exercise
A colleague computes v_max over all items, including one with value 10,000 and weight larger than the capacity. All other items have values below 100. What goes wrong?
Show answer
K becomes ε · 10,000 / n, which is far larger than any value that can actually be packed. Every packable item may round to 0, so the DP cannot tell items apart and may return an arbitrary or empty set. The proof fails at the step vmax ≤ OPT, because the item with value vmax cannot fit. Filter out items heavier than the capacity before computing v_max.
Exercise
Why does the code clamp K to at least 1, and does the clamp break the (1 − ε) guarantee?
Show answer
If ε · vmax / n < 1, then dividing by K would make the rounded values larger than the originals and the DP slower than the exact one. With integer values, K = 1 does no rounding, so the DP is exact and returns OPT, which satisfies the guarantee. The running time is then O(n · V) with V ≤ n · vmax < n²/ε, so it stays within the FPTAS bound.