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 fraction of the optimum, and the grid is fine enough that the dynamic program stays polynomial in and . The scheme is due to Ibarra and Kim (1975), the first FPTAS.
An exact algorithm with profits as the index
Items have profits and sizes , all positive integers, and the capacity is ; assume for every item. The familiar dynamic program over capacities runs in time (0/1 Knapsack in the practice area). For the FPTAS we need the dual formulation, indexed by profit:
with , for , and . The optimum is the largest with . With , profits range up to , so the table has entries and the running time is : pseudo-polynomial, like the subset-sum program of Subset Sum.
Scaling
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 SThe rounded profits are at most , so the dynamic program takes time: polynomial in and .
Theorem (Ibarra and Kim, 1975). The set returned satisfies .
Proof. Let be an optimal set. Rounding down loses less than per item: . Since is optimal for ,
where the last step uses : the most profitable item fits on its own.
The loss is at most in absolute terms. The whole trick is to make a small fraction of a quantity that is at most OPT, here the largest profit .
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 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 assumes every item loses almost .
In C++
The same scheme with a one-dimensional table and a separate bit table for reconstructing the chosen items.
#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 ) 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 of a smaller kept sum, with . Each trimming step loses at most a factor , the steps together at most , and the list stays short because its kept values grow geometrically: at most entries.
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 ), 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 would make the answer exact, but then , 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 by treating large and small items differently: only items with profit above need the table; small ones are added greedily by density at the end. Later work has brought the dependence on 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?
- It is faster for every input
- Scaling changes the profits, not the sizes, so only a table over profits becomes small after rounding
- Capacities cannot be integers
- To avoid recursion
Which step of the proof uses ?
- Bounding the running time
- Turning the absolute loss into a relative loss of at most
- Showing is feasible
- Rounding down the profits
What is the running time of the Ibarra-Kim scheme with the profit-indexed DP?