Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Approximating Knapsack

Rounding values into a fully polynomial-time approximation scheme.

Knapsack is NP-hard, yet for every ε>0\varepsilon>0 you can find a packing worth at least 1−ε1-\varepsilon times the optimum in time polynomial in both nn and 1/ε1/\varepsilon. The trick is to throw precision away on purpose: round every value onto a coarse grid, and the pseudo-polynomial table over values becomes a polynomial one.

What you’ll learn

  • Define α\alpha-approximation, PTAS and FPTAS, and place knapsack, bin packing, scheduling and TSP among them.
  • Prove that the better of the greedy prefix and the single most valuable item is a 12\tfrac12-approximation, with the fractional relaxation as the upper bound.
  • Build the FPTAS: scale the values by K=εvmax⁡/nK=\varepsilon v_{\max}/n, solve the table over scaled values, and prove the (1−ε)(1-\varepsilon) guarantee and the O(n3/ε)O(n^3/\varepsilon) running time.
  • Prove that a strongly NP-hard problem with polynomially bounded integer optimum has no FPTAS unless P = NP, and describe the state of the art, O~(n+1/ε2)\tilde O(n+1/\varepsilon^2), and why it is believed optimal.

Approximation schemes, and a first guarantee

ProblemWhat is achievable
0/1 knapsackAn FPTAS (Ibarra & Kim, 1975); a PTAS came first (Sahni, 1975)
Scheduling on mm identical machines, mm part of the inputA PTAS (Hochbaum & Shmoys, 1987) but no FPTAS unless P = NP
Bin packingNo ratio below 3/23/2 unless P = NP: deciding whether 2 bins suffice is partition
Metric TSPRatio 3/23/2 (Christofides), and no PTAS unless P = NP
Euclidean TSP in the planeA PTAS (Arora, 1998; Mitchell, 1999)
The ladder from weakest to strongest guarantee: constant ratio, PTAS, FPTAS, exact.

A quick constant-factor algorithm comes first. Drop the items heavier than WW (they never fit) and sort the rest by value per weight, vi/wiv_i/w_i, best first. Greedy takes items in this order while they fit and stops at the first item kk that does not, the critical item; call the value taken GG. Greedy alone can be terrible: with items (w=1,v=2)(w=1,v=2) and (w=W,v=W)(w=W,v=W) it takes the first, cannot add the second, and gets 2 against an optimum of WW. One extra candidate repairs it.

DerivationProof through the fractional relaxation
  1. OPT ≤ OPTfrac = G+f vk < G+vk\mathrm{OPT}\ \le\ \mathrm{OPT}_{\text{frac}}\ =\ G+f\,v_k\ <\ G+v_k

    Allow fractions of items: this relaxation can only raise the optimum. Its optimum is the greedy prefix plus the fitting fraction f∈[0,1)f\in[0,1) of the critical item (an exchange argument: see Proving Greedy Algorithms Correct):

  2. OPT < G+vmax⁡ ≤ 2max⁡(G, vmax⁡)\mathrm{OPT}\ <\ G+v_{\max}\ \le\ 2\max(G,\,v_{\max})

    The critical item fits alone, so vk≤vmax⁡v_k\le v_{\max}, and a sum of two numbers is at most twice the larger one:

  3. 12 OPT ≤ max⁡(G,vmax⁡) ≤ OPT ≤ G+f vk\tfrac12\,\mathrm{OPT}\ \le\ \max(G,v_{\max})\ \le\ \mathrm{OPT}\ \le\ G+f\,v_k

    Sorting dominates, so the algorithm runs in O(nlog⁡n)O(n\log n) time. The fractional optimum G+fvkG+f v_k is also a cheap upper bound on OPT\mathrm{OPT}, which branch-and-bound codes use to prune.

A table indexed by value

The FPTAS rests on the table of Pseudo-Polynomial Time that is indexed by value rather than weight. Let leasti(q)\mathrm{least}_i(q) be the least total weight of a subset of the first ii items whose total value is exactly qq (∞\infty if there is none):

leasti(q)=min⁡(leasti−1(q), leasti−1(q−vi−1)+wi−1),least0(0)=0.\mathrm{least}_i(q)=\min\big(\mathrm{least}_{i-1}(q),\ \mathrm{least}_{i-1}(q-v_{i-1})+w_{i-1}\big),\qquad \mathrm{least}_0(0)=0.

The optimum is the largest qq with leastn(q)≤W\mathrm{least}_n(q)\le W. With V=∑ivi≤n vmax⁡V=\sum_iv_i\le n\,v_{\max} the table costs Θ(nV)=O(n2vmax⁡)\Theta(nV)=O(n^2v_{\max}) time: polynomial in nn and in the values, independent of the weights and of WW.

Think first If every value were an integer between 1 and nn, how fast would this table solve knapsack exactly?

V≤n2V\le n^2, so the table takes O(n3)O(n^3) time: polynomial. Knapsack is hard only because the values (or the weights) can be huge. The FPTAS forces the values into that small range by rounding, and pays for it with a small loss.

Round, solve, and prove

Drop the items heavier than WW, so that every remaining item fits alone and OPT≥vmax⁡\mathrm{OPT}\ge v_{\max}. Fix ε∈(0,1)\varepsilon\in(0,1) and a grid step K=εvmax⁡/nK=\varepsilon v_{\max}/n, round every value down onto the grid, vi′=⌊vi/K⌋v_i'=\lfloor v_i/K\rfloor, and solve the table over the scaled values v′v' exactly. Return the subset it finds, valued with the original vv. This is the scheme of Ibarra and Kim (1975) in its simplest form.

python
def knapsack_fptas(weights, values, W, eps):
    """Items with total value >= (1 - eps) * OPT, in O(n^3 / eps) time."""
    items = [i for i in range(len(weights)) if weights[i] <= W]   # heavier items never fit
    if not items:
        return []
    K = eps * max(values[i] for i in items) / len(items)
    scaled = [int(values[i] // K) for i in items]          # values rounded down to a grid of step K
    V = sum(scaled)
    least = [0] + [float('inf')] * V                       # least[q]: least weight, scaled value q
    took = [[False] * (V + 1) for _ in items]
    for j, i in enumerate(items):
        for q in range(V, scaled[j] - 1, -1):
            if least[q - scaled[j]] + weights[i] < least[q]:
                least[q] = least[q - scaled[j]] + weights[i]
                took[j][q] = True
    q = max(q for q in range(V + 1) if least[q] <= W)
    chosen = []
    for j in range(len(items) - 1, -1, -1):                # walk the choices back
        if took[j][q]:
            chosen.append(items[j])
            q -= scaled[j]
    return chosen[::-1]

print(knapsack_fptas([6, 8, 1, 9], [40, 48, 38, 80], 9, 0.5))   # [3]: value 80, optimum 86

The table over scaled values, with one bit per cell (took) to walk the choices back: the last pass that improved least[q]\mathrm{least}[q] took item jj.

DerivationThe guarantee: at least (1 − ε)·OPT
  1. K vi′ ≤ vi < K vi′+KK\,v_i'\ \le\ v_i\ <\ K\,v_i'+K

    Rounding down loses less than one grid step per item:

  2. v(S) ≥ K v′(S) ≥ K v′(O) ≥ ∑i∈O(vi−K) ≥ OPT−nKv(S)\ \ge\ K\,v'(S)\ \ge\ K\,v'(O)\ \ge\ \sum_{i\in O}(v_i-K)\ \ge\ \mathrm{OPT}-nK

    Let OO be an optimal set and SS the set returned. SS is the best feasible set for the scaled values, so v′(S)≥v′(O)v'(S)\ge v'(O). Chain the inequalities, losing less than KK for each of the at most nn items of OO:

  3. v(S) ≥ OPT−ε vmax⁡ ≥ (1−ε) OPTv(S)\ \ge\ \mathrm{OPT}-\varepsilon\,v_{\max}\ \ge\ (1-\varepsilon)\,\mathrm{OPT}

    By the choice of KK, the total loss is nK=εvmax⁡nK=\varepsilon v_{\max}, and vmax⁡≤OPTv_{\max}\le\mathrm{OPT} because the most valuable item fits alone:

DerivationThe running time: O(n³/ε)
  1. V′=∑ivi′ ≤ n⋅nε=n2εV'=\sum_i v_i'\ \le\ n\cdot\frac{n}{\varepsilon}=\frac{n^2}{\varepsilon}

    Every scaled value is at most vmax⁡/K=n/εv_{\max}/K=n/\varepsilon, so the scaled total is small:

  2. O(n V′)=O ⁣(n3ε)O(n\,V')=O\!\left(\frac{n^3}{\varepsilon}\right)

    The table has nn rows of V′+1V'+1 cells, each filled in O(1)O(1):

  3. ε=0.01, n=100:n V′≤n3ε=108\varepsilon=0.01,\ n=100:\quad n\,V'\le\frac{n^3}{\varepsilon}=10^8

    That is polynomial in nn and 1/ε1/\varepsilon, with no dependence on the sizes of the weights or values beyond O(1)O(1)-time arithmetic: a fully polynomial-time approximation scheme. Lawler (1979) cut the time to O(nlog⁡(1/ε)+1/ε4)O(n\log(1/\varepsilon)+1/\varepsilon^4) by rounding more cleverly and treating small items greedily.

ItemWeightValue vvScaled v′=⌊v/10⌋v'=\lfloor v/10\rfloor
A6404
B8484
C1383
D9808
Capacity 9 and ε=1/2\varepsilon=1/2, so K=12⋅80/4=10K=\tfrac12\cdot80/4=10. The feasible sets worth most are B + C (value 86, the optimum), D (80) and A + C (78).
Predict before you look

On this instance, the scheme with ε=1/2\varepsilon=1/2 solves the scaled problem exactly and returns its set. What is the original value of the set it returns?

Show the answer

80

In scaled values D is worth 8, while B + C and A + C are worth only 4+3=74+3=7: rounding cost B and C 8 units each but D nothing. So the scheme returns D, worth 80, while the optimum is 86. The guarantee promises at least OPT−nK=86−40=46\mathrm{OPT}-nK=86-40=46; the actual ratio is 80/86≈0.9380/86\approx0.93. With ε=0.1\varepsilon=0.1 the grid is fine enough to return B + C.

Limits, and the state of the art

DerivationProof: a fine enough ε is exact
  1. A ≥ (1−ε) OPT = OPT−ε OPT > OPT−1A\ \ge\ (1-\varepsilon)\,\mathrm{OPT}\ =\ \mathrm{OPT}-\varepsilon\,\mathrm{OPT}\ >\ \mathrm{OPT}-1

    Run the scheme with ε=1/p(Length(I),Max(I))\varepsilon=1/p(\mathrm{Length}(I),\mathrm{Max}(I)). For a maximization problem it returns a value AA with

  2. time=poly(Length(I), Max(I))\mathrm{time}=\mathrm{poly}\big(\mathrm{Length}(I),\ \mathrm{Max}(I)\big)

    AA and OPT\mathrm{OPT} are integers and A≤OPTA\le\mathrm{OPT}, so A=OPTA=\mathrm{OPT}: the answer is exact (minimization is symmetric). The time is polynomial in Length(I)\mathrm{Length}(I) and 1/ε=p(Length(I),Max(I))1/\varepsilon=p(\mathrm{Length}(I),\mathrm{Max}(I)):

  3. FPTAS ⇒ pseudo-polynomial ⇒ P=NP(if strongly NP-hard)\text{FPTAS}\ \Rightarrow\ \text{pseudo-polynomial}\ \Rightarrow\ \mathrm{P}=\mathrm{NP}\quad\text{(if strongly NP-hard)}

    That is a pseudo-polynomial exact algorithm, which a strongly NP-hard problem has only if P = NP (Pseudo-Polynomial Time). Bin packing (optimum at most nn) and scheduling on mm machines with mm in the input (optimum at most the total processing time) are examples: PTAS-type results are the best one can hope for.

Check your understanding

Scheduling jobs on mm identical machines to minimize the finishing time, with mm part of the input, is strongly NP-hard and has a PTAS (Hochbaum & Shmoys, 1987). Which further result would show that P = NP?

  1. A PTAS whose running time is nO(1/ε2)n^{O(1/\varepsilon^2)}
  2. An FPTAS
  3. A 43\tfrac43-approximation in O(nlog⁡n)O(n\log n) time
  4. An exact algorithm in O(2n poly(n))O(2^n\,\mathrm{poly}(n)) time
Show the answer

B. An FPTAS

The optimum is an integer bounded by the total processing time, which is at most the unary length of the instance. An FPTAS run with ε\varepsilon below one over that bound would be an exact pseudo-polynomial algorithm for a strongly NP-hard problem, so it would show that P = NP.

For knapsack itself, the question is how fast an FPTAS can be. Sahni (1975) gave a PTAS that tries all small sets of items and fills up greedily; Ibarra and Kim (1975) gave the first FPTAS; Lawler (1979) and many later papers refined the rounding. In this century the target became running times of the form O~(n+(1/ε)c)\tilde O(n+(1/\varepsilon)^c): c=12/5c=12/5 (Chan, 2018), c=11/5c=11/5 (Deng, Jin & Mao, 2023), and finally c=2c=2, found independently by Mao and by Chen, Lian, Mao and Zhang (2024). For unbounded knapsack, O~(n+1/ε2)\tilde O(n+1/\varepsilon^2) was known earlier (Jansen & Kraft).

Key takeaways

  • A PTAS is polynomial for each fixed ε\varepsilon; an FPTAS is polynomial in nn and 1/ε1/\varepsilon. Knapsack has an FPTAS; strongly NP-hard problems with polynomially bounded integer optima do not, unless P = NP.
  • Greedy by value per weight can be arbitrarily bad, but the better of the greedy prefix and the best single item is within a factor 2, because the fractional optimum is at most G+vmax⁡G+v_{\max}.
  • The FPTAS rounds values down to multiples of K=εvmax⁡/nK=\varepsilon v_{\max}/n, solves the table over scaled values in O(n3/ε)O(n^3/\varepsilon), and loses at most nK=εvmax⁡≤ε OPTnK=\varepsilon v_{\max}\le\varepsilon\,\mathrm{OPT}.
  • The fastest schemes run in O~(n+1/ε2)\tilde O(n+1/\varepsilon^2) (2024), and a (min⁡,+)(\min,+)-convolution lower bound says the exponent 2 cannot be lowered.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which running time, for every ε>0\varepsilon>0, makes a (1−ε)(1-\varepsilon)-approximation algorithm an FPTAS?

  1. O(n1/ε)O(n^{1/\varepsilon})
  2. O(21/ε n)O(2^{1/\varepsilon}\,n)
  3. O(n2/ε3)O(n^2/\varepsilon^3)
  4. O(nW)O(nW)
Show the answer

C. O(n2/ε3)O(n^2/\varepsilon^3)

An FPTAS must be polynomial in both nn and 1/ε1/\varepsilon. n1/εn^{1/\varepsilon} is polynomial for each fixed ε\varepsilon but not in 1/ε1/\varepsilon (a PTAS), and 21/εn2^{1/\varepsilon}n is exponential in 1/ε1/\varepsilon (also only a PTAS).

Question 2

The FPTAS sets the grid step to K=εvmax⁡/nK=\varepsilon v_{\max}/n. Why vmax⁡v_{\max} and not OPT\mathrm{OPT}, which would give a coarser grid?

  1. vmax⁡v_{\max} is larger than OPT\mathrm{OPT}, so the grid is safer
  2. OPT\mathrm{OPT} is unknown, while vmax⁡v_{\max} is computable and satisfies vmax⁡≤OPT≤n vmax⁡v_{\max}\le\mathrm{OPT}\le n\,v_{\max}
  3. Rounding must use an item's value, not a sum of values
  4. Any constant would do; the choice affects only the running time
Show the answer

B. OPT\mathrm{OPT} is unknown, while vmax⁡v_{\max} is computable and satisfies vmax⁡≤OPT≤n vmax⁡v_{\max}\le\mathrm{OPT}\le n\,v_{\max}

Every item fits alone, so OPT≥vmax⁡\mathrm{OPT}\ge v_{\max}, and the total loss nK=εvmax⁡nK=\varepsilon v_{\max} is then at most ε OPT\varepsilon\,\mathrm{OPT}. The upper bound OPT≤nvmax⁡\mathrm{OPT}\le nv_{\max} keeps the scaled values at most n/εn/\varepsilon each, which bounds the table.

Question 3

Items: XX with w=1,v=2w=1, v=2 and YY with w=10,v=10w=10, v=10; capacity 10. What do plain greedy (by value per weight) and "greedy or the best single item" return?

  1. Both return 10
  2. Plain greedy 2, the repaired version 10
  3. Plain greedy 12, the repaired version 12
  4. Both return 2
Show the answer

B. Plain greedy 2, the repaired version 10

Greedy takes XX (ratio 2), and then YY no longer fits: value 2. The repaired version compares with the best single item, YY worth 10, which is optimal here. Without the repair the ratio 2/W2/W can be made arbitrarily small.

Question 4

Bin packing is strongly NP-hard, and its optimum is an integer between 1 and nn. What does this imply?

  1. It has an FPTAS, because its optimum is small
  2. It has no FPTAS unless P = NP: running one with ε<1/n\varepsilon<1/n would solve it exactly in polynomial time
  3. It has no approximation algorithm with any constant ratio
  4. Nothing: strong NP-hardness concerns exact algorithms only
Show the answer

B. It has no FPTAS unless P = NP: running one with ε<1/n\varepsilon<1/n would solve it exactly in polynomial time

For a minimization problem with integer optimum at most nn, a (1+ε)(1+\varepsilon)-approximation with ε<1/n\varepsilon<1/n is off by less than 1, hence exact, and an FPTAS would deliver it in time polynomial in nn. That would solve a strongly NP-hard problem in polynomial time.

Further reading

  • O. H. Ibarra & C. E. Kim, "Fast approximation algorithms for the knapsack and sum of subset problems," Journal of the ACM 22(4) (1975), 463–468.
  • E. L. Lawler, "Fast approximation algorithms for knapsack problems," Mathematics of Operations Research 4(4) (1979), 339–356.
  • V. V. Vazirani, Approximation Algorithms (Springer, 2001), chapter 8, "Knapsack".
  • D. P. Williamson & D. B. Shmoys, The Design of Approximation Algorithms (Cambridge, 2011), §3.1.
  • X. Mao, "(1 − ε)-Approximation of Knapsack in Nearly Quadratic Time," STOC 2024; independently L. Chen, J. Lian, Y. Mao & G. Zhang, "A Nearly Quadratic-Time FPTAS for Knapsack" (2024).