TExcelTAD
Home › Approximation Algorithms › A Knapsack FPTAS by Profit Scaling

A Knapsack FPTAS by Profit Scaling

Knapsack is NP-hard, but only "weakly": it has an exact algorithm whose running time is polynomial in the number of items and the magnitude of the numbers. Approximation turns that into a fully polynomial scheme. Round the profits to a coarse grid, so that the numbers become small, and solve the rounded instance exactly. The rounding loses at most an ε\varepsilon fraction of the optimum, and the grid is fine enough that the dynamic program stays polynomial in nn and 1ε\frac{1}{\varepsilon}. The scheme is due to Ibarra and Kim (1975), the first FPTAS.

An exact algorithm with profits as the index

Items 1,…,n1, \ldots, n have profits pip_i and sizes sis_i, all positive integers, and the capacity is BB; assume si≤Bs_i \le B for every item. The familiar dynamic program over capacities runs in O(nB)O(nB) time (0/1 Knapsack in the practice area). For the FPTAS we need the dual formulation, indexed by profit:

A(i,p)=the smallest total size of a subset of items 1..i with total profit exactly p,A(i, p) = \text{the smallest total size of a subset of items } 1..i \text{ with total profit exactly } p,

with A(0,0)=0A(0, 0) = 0, A(0,p)=∞A(0, p) = \infty for p>0p > 0, and A(i,p)=min⁡(A(i−1,p), si+A(i−1,p−pi))A(i, p) = \min\left(A(i-1, p),\ s_i + A(i-1, p - p_i)\right). The optimum is the largest pp with A(n,p)≤BA(n, p) \le B. With P=max⁡ipiP = \max_i p_i, profits range up to nPnP, so the table has O(n2P)O(n^2 P) entries and the running time is O(n2P)O(n^2 P): pseudo-polynomial, like the subset-sum program of Subset Sum.

Scaling

text
KNAPSACK-FPTAS(p, s, B, eps)
1  K = eps * P / n                        -- P = the largest profit
2  p'_i = floor(p_i / K) for every item   -- rounded profits, at most n / eps
3  S = an optimal set for the profits p' (the profit-indexed DP)
4  return S

The rounded profits are at most PK=nε\frac{P}{K} = \frac{n}{\varepsilon}, so the dynamic program takes O(n2⋅nε)=O(n3ε)O(n^2 \cdot \frac{n}{\varepsilon}) = O(\frac{n^3}{\varepsilon}) time: polynomial in nn and 1ε\frac{1}{\varepsilon}.

Theorem (Ibarra and Kim, 1975). The set SS returned satisfies p(S)≥(1−ε) OPTp(S) \ge (1 - \varepsilon)\,\text{OPT}.

Proof. Let OO be an optimal set. Rounding down loses less than KK per item: Kpi′>pi−KK p'_i > p_i - K. Since SS is optimal for p′p',

p(S)≥K∑i∈Spi′≥K∑i∈Opi′>∑i∈O(pi−K)≥OPT−nK=OPT−εP≥(1−ε) OPT,p(S) \ge K \sum_{i \in S} p'_i \ge K \sum_{i \in O} p'_i > \sum_{i \in O} (p_i - K) \ge \text{OPT} - nK = \text{OPT} - \varepsilon P \ge (1 - \varepsilon)\,\text{OPT},

where the last step uses OPT≥P\text{OPT} \ge P: the most profitable item fits on its own. □\square

The loss is at most nKnK in absolute terms. The whole trick is to make nKnK a small fraction of a quantity that is at most OPT, here the largest profit PP.

python · try it yourself
import random

def best_by_profit(profits, sizes, B):
    """Profit-indexed DP: returns (best profit, chosen items, number of table cells)."""
    total = sum(profits)
    INF = float("inf")
    A = [0] + [INF] * total
    choice = [[False] * (total + 1) for _ in profits]
    for i, (p, s) in enumerate(zip(profits, sizes)):
        for q in range(total, p - 1, -1):
            if A[q - p] + s < A[q]:
                A[q] = A[q - p] + s
                choice[i][q] = True
    q = max(q for q in range(total + 1) if A[q] <= B)
    best, chosen = q, []
    for i in reversed(range(len(profits))):
        if choice[i][q]:
            chosen.append(i)
            q -= profits[i]
    return best, sorted(chosen), len(profits) * (total + 1)

def fptas(profits, sizes, B, eps):
    K = eps * max(profits) / len(profits)
    rounded = [int(p // K) for p in profits]
    _, chosen, cells = best_by_profit(rounded, sizes, B)
    return sum(profits[i] for i in chosen), cells

rng = random.Random(2)
n = 25
sizes = [rng.randint(10, 100) for _ in range(n)]
profits = [10 * s + rng.randint(0, 40) for s in sizes]      # profit close to 10 x size: a hard type
B = sum(sizes) // 3
opt, _, cells = best_by_profit(profits, sizes, B)
print(f"exact: profit {opt}, {cells} table cells")
for eps in [0.9, 0.5, 0.2, 0.1, 0.05]:
    val, cells = fptas(profits, sizes, B, eps)
    print(f"eps = {eps:4}: profit {val}, ratio {val / opt:.4f} >= {1 - eps:.2f}, {cells:7} table cells")
exact: profit 4938, 360825 table cells
eps =  0.9: profit 4870, ratio 0.9862 >= 0.10,    9900 table cells
eps =  0.5: profit 4899, ratio 0.9921 >= 0.50,   18050 table cells
eps =  0.2: profit 4932, ratio 0.9988 >= 0.80,   45625 table cells
eps =  0.1: profit 4938, ratio 1.0000 >= 0.90,   91700 table cells
eps = 0.05: profit 4938, ratio 1.0000 >= 0.95,  183600 table cells

The instance is of the hard kind for knapsack algorithms, with every profit close to ten times the size, so that all items look alike and the choice depends on small differences, exactly what rounding blurs. The table size grows like n2ε\frac{n^2}{\varepsilon} while the exact table grows with the profits themselves. Still, the scaled solutions are much closer to optimal than the guarantee: rounding errors partly cancel, and the bound nKnK assumes every item loses almost KK.

In C++

The same scheme with a one-dimensional table and a separate bit table for reconstructing the chosen items.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <limits>
#include <vector>

std::vector<int> best_set(const std::vector<int>& p, const std::vector<int>& s, int B) {
    int n = p.size(), total = 0;
    for (int x : p) total += x;
    const long long INF = std::numeric_limits<long long>::max() / 2;
    std::vector<long long> A(total + 1, INF);
    std::vector<std::vector<char>> take(n, std::vector<char>(total + 1, 0));
    A[0] = 0;
    for (int i = 0; i < n; i++)
        for (int q = total; q >= p[i]; q--)
            if (A[q - p[i]] + s[i] < A[q]) { A[q] = A[q - p[i]] + s[i]; take[i][q] = 1; }
    int q = total;
    while (A[q] > B) q--;
    std::vector<int> chosen;
    for (int i = n - 1; i >= 0; i--) if (take[i][q]) { chosen.push_back(i); q -= p[i]; }
    return chosen;
}

int main() {
    std::vector<int> p = {1530, 980, 1720, 640, 1210, 1870, 450, 1330, 760, 1990, 1105, 870};
    std::vector<int> s = {52, 31, 70, 18, 44, 81, 12, 50, 25, 95, 41, 29};
    int B = 200;
    auto value = [&](const std::vector<int>& S) { int v = 0; for (int i : S) v += p[i]; return v; };
    int opt = value(best_set(p, s, B));
    std::printf("exact optimum %d\n", opt);
    for (double eps : {0.5, 0.25, 0.1}) {
        double K = eps * *std::max_element(p.begin(), p.end()) / p.size();
        std::vector<int> r;
        for (int x : p) r.push_back((int)(x / K));
        int v = value(best_set(r, s, B));
        std::printf("eps = %.2f: K = %.2f, profit %d, ratio %.4f\n", eps, K, v, (double)v / opt);
    }
}
exact optimum 6015
eps = 0.50: K = 82.92, profit 5990, ratio 0.9958
eps = 0.25: K = 41.46, profit 5990, ratio 0.9958
eps = 0.10: K = 16.58, profit 6015, ratio 1.0000

Trimming: an FPTAS for subset sum

Subset sum (maximize a subset's total without exceeding a target tt) has an FPTAS of a different flavour. The exact algorithm keeps the list of all reachable sums, which can have exponential length. Trimming deletes every sum that is within a factor 1+δ1 + \delta of a smaller kept sum, with δ=ε2n\delta = \frac{\varepsilon}{2n}. Each trimming step loses at most a factor 1+δ1 + \delta, the nn steps together at most (1+δ)n≤eε/2≤1+ε(1 + \delta)^n \le e^{\varepsilon/2} \le 1 + \varepsilon, and the list stays short because its kept values grow geometrically: at most log⁡1+δt=O(nlog⁡tε)\log_{1+\delta} t = O(\frac{n \log t}{\varepsilon}) entries.

python · try it yourself
import random

def best_sum(nums, t, eps=None):
    L, longest = [0], 1
    delta = eps / (2 * len(nums)) if eps else 0
    for x in nums:
        merged = sorted(set(L + [v + x for v in L if v + x <= t]))
        if eps:
            trimmed = [merged[0]]
            for v in merged[1:]:
                if v > trimmed[-1] * (1 + delta):
                    trimmed.append(v)
            merged = trimmed
        L = merged
        longest = max(longest, len(L))
    return L[-1], longest

rng = random.Random(9)
nums = [rng.randint(10 ** 5, 10 ** 6) for _ in range(18)]
t = sum(nums) // 3
exact, size = best_sum(nums, t)
print(f"exact: best sum {exact} (target {t}), longest list {size}")
for eps in [0.5, 0.1, 0.01]:
    val, size = best_sum(nums, t, eps)
    print(f"eps = {eps:4}: best sum {val}, ratio {val / exact:.5f}, longest list {size}")
exact: best sum 3032906 (target 3032943), longest list 26156
eps =  0.5: best sum 3032142, ratio 0.99975, longest list 108
eps =  0.1: best sum 3022485, ratio 0.99656, longest list 415
eps = 0.01: best sum 3032365, ratio 0.99982, longest list 2474

The exact list reaches tens of thousands of entries (and could grow towards 2182^{18}), the trimmed ones stay far shorter, and every answer is within half a percent of the exact one, much better than the guarantee. The practice problem Subset Sum asks for the exact decision version, where the numbers are small enough for the pseudo-polynomial table.

Why this does not contradict NP-hardness

The scheme gets arbitrarily close to OPT, but never exactly there in polynomial time: choosing ε<1OPT\varepsilon < \frac{1}{\text{OPT}} would make the answer exact, but then 1ε\frac{1}{\varepsilon}, and with it the running time, is as large as the profits, and we are back to the pseudo-polynomial algorithm. This is the argument of PTAS, FPTAS and the Class APX read in reverse: an FPTAS exists only for problems that are not strongly NP-hard, and knapsack is the archetype.

Refinements and relatives

  • Faster schemes. Lawler (1979) reduced the running time to O(nlog⁡1ε+1ε4)O(n \log \frac{1}{\varepsilon} + \frac{1}{\varepsilon^4}) by treating large and small items differently: only items with profit above ε OPT\varepsilon\,\text{OPT} need the table; small ones are added greedily by density at the end. Later work has brought the dependence on 1ε\frac{1}{\varepsilon} much closer to quadratic.
  • Multidimensional knapsack (several capacity constraints) has a PTAS for a constant number of dimensions but no FPTAS unless P = NP, already with two constraints (Magazine and Chern, 1984).
  • Rounding the input reappears throughout the section: bin packing groups item sizes (An Asymptotic PTAS for Bin Packing), Euclidean TSP snaps points to a grid (Euclidean TSP: the Idea of Arora's PTAS).

Test yourself

Why does the FPTAS use a dynamic program indexed by profit instead of by capacity?

  1. It is faster for every input
  2. Scaling changes the profits, not the sizes, so only a table over profits becomes small after rounding
  3. Capacities cannot be integers
  4. To avoid recursion

Which step of the proof uses OPT≥P\text{OPT} \ge P?

  1. Bounding the running time
  2. Turning the absolute loss nK=εPnK = \varepsilon P into a relative loss of at most ε OPT\varepsilon\,\text{OPT}
  3. Showing SS is feasible
  4. Rounding down the profits

What is the running time of the Ibarra-Kim scheme with the profit-indexed DP?

  1. O(n1/ε)O(n^{1/\varepsilon})
  2. O(n3ε)O(\frac{n^3}{\varepsilon})
  3. O(2n)O(2^n)
  4. O(nB)O(nB)