TExcelTAD

Fractional and 0/1 Knapsack

Two knapsack problems look almost identical. In the 0/1 knapsack of an earlier lesson, each item is taken whole or left behind; the problem is NP-hard and needs a pseudo-polynomial DP. In the fractional knapsack, items are divisible, like gold dust, flour or bandwidth, and any fraction of an item may be taken for the same fraction of its value. That one change makes a simple greedy algorithm optimal. Comparing the two is the clearest way to see what the greedy-choice property is and why it can fail.

The greedy algorithm

Items 1..n1..n have weights wi>0w_i > 0 and values vi≥0v_i \ge 0; capacity WW. Choose fractions xi∈[0,1]x_i \in [0, 1] with ∑ixiwi≤W\sum_i x_i w_i \le W maximising ∑ixivi\sum_i x_i v_i.

The natural measure is the value density ρi=vi/wi\rho_i = v_i / w_i, value per kilogram. Greedy: sort by density, decreasing, take whole items while they fit, then take the fraction of the next item that fills the bag exactly.

text
FRACTIONAL-KNAPSACK(w, v, W)
1  sort the items so that v[0]/w[0] >= v[1]/w[1] >= ... >= v[n-1]/w[n-1]
2  room = W;  total = 0
3  for i = 0 to n - 1
4      if room == 0
5          break
6      take = min(w[i], room)          // all of item i, or what still fits
7      total = total + v[i] * take / w[i]
8      room = room - take
9  return total

The program uses the four items of the 0/1 knapsack lesson, with exact fractions.

python · try it yourself
from fractions import Fraction

def fractional_knapsack(weights, values, W):
    order = sorted(range(len(weights)), key=lambda i: Fraction(values[i], weights[i]), reverse=True)
    room, total, plan = W, Fraction(0), []
    for i in order:
        if room == 0:
            break
        take = min(weights[i], room)
        total += Fraction(values[i] * take, weights[i])
        plan.append((i + 1, Fraction(take, weights[i])))
        room -= take
    return total, plan

weights, values, W = [4, 3, 2, 5], [10, 7, 4, 12], 10
print("densities:", [str(Fraction(v, w)) for w, v in zip(weights, values)])
total, plan = fractional_knapsack(weights, values, W)
for item, frac in plan:
    print(f"  item {item}: take {frac} of it")
print("fractional optimum:", total, "=", round(float(total), 3))
densities: ['5/2', '7/3', '2', '12/5']
  item 1: take 1 of it
  item 4: take 1 of it
  item 2: take 1/3 of it
fractional optimum: 73/3 = 24.333

The densities are 2.52.5, 2.332.33, 22 and 2.42.4. Greedy takes all of item 1 and item 4 (9 kilograms, value 22), then one third of item 2 for the last kilogram: 22+73=241322 + \frac{7}{3} = 24\frac{1}{3}. The 0/1 optimum for the same items is 23, so the ability to split is worth a third of a unit here.

Why greedy is optimal here

Greedy choice. Let item 1 have the highest density. Some optimal solution takes as much of item 1 as possible, namely min⁡(w1,W)\min(w_1, W) kilograms.

Exchange argument. Take an optimal solution that uses less of item 1 than that. Then either the bag has unused room, and adding more of item 1 increases the value (or leaves it unchanged if v1=0v_1 = 0), or it contains some amount δ>0\delta > 0 of another item jj. Replace δ\delta kilograms of item jj by δ\delta kilograms of item 1 (as much as is still available). The weight is unchanged and the value changes by δ(ρ1−ρj)≥0\delta(\rho_1 - \rho_j) \ge 0. Repeating this until item 1 is maxed out gives an optimal solution that makes the greedy choice. ■\blacksquare

Optimal substructure. After taking min⁡(w1,W)\min(w_1, W) of item 1, what remains is a fractional knapsack with the other items and capacity W−min⁡(w1,W)W - \min(w_1, W), and an optimal solution of it plus the greedy choice is optimal overall (cut and paste). Induction finishes the proof.

The running time is Θ(nlg⁡n)\Theta(n \lg n) for the sort. It can even be done in Θ(n)\Theta(n): find the "critical" item, the one that ends up split, with a weighted-median selection in the style of quickselect, without sorting the rest.

Why greedy fails for 0/1

Run the same exchange argument for 0/1 and it breaks at one step: "replace δ\delta kilograms of item jj by item 1" is no longer allowed, because items come whole. Swapping all of item jj for all of item 1 may not fit, or may leave room that nothing else can fill. The greedy-choice property itself is false: in the example, the item with the highest density, item 1, is not in the only optimal 0/1 solution, items 2, 3 and 4.

The program shows three numbers for many random instances: the fractional optimum (greedy), the 0/1 optimum (DP), and the 0/1 solution that the greedy rule produces when it may only take whole items.

python · try it yourself
import random
from fractions import Fraction

def fractional(weights, values, W):
    total, room = Fraction(0), W
    for w, v in sorted(zip(weights, values), key=lambda p: Fraction(p[1], p[0]), reverse=True):
        take = min(w, room)
        total += Fraction(v * take, w)
        room -= take
    return total

def zero_one(weights, values, W):
    K = [0] * (W + 1)
    for w, v in zip(weights, values):
        for c in range(W, w - 1, -1):
            K[c] = max(K[c], K[c - w] + v)
    return K[W]

def greedy_whole(weights, values, W):
    total, room = 0, W
    for w, v in sorted(zip(weights, values), key=lambda p: Fraction(p[1], p[0]), reverse=True):
        if w <= room:
            total += v
            room -= w
    return total

ex = ([4, 3, 2, 5], [10, 7, 4, 12], 10)
print(f"the example: fractional {fractional(*ex)}, 0/1 optimum {zero_one(*ex)}, greedy-whole {greedy_whole(*ex)}")
rng = random.Random(6)
worst_ratio, ok = 1.0, True
for _ in range(2000):
    n = rng.randint(1, 8)
    weights = [rng.randint(1, 20) for _ in range(n)]
    values = [rng.randint(0, 30) for _ in range(n)]
    W = rng.randint(1, 40)
    frac, opt, gw = fractional(weights, values, W), zero_one(weights, values, W), greedy_whole(weights, values, W)
    ok &= frac >= opt >= gw
    best_single = max([v for w, v in zip(weights, values) if w <= W], default=0)
    if opt > 0:
        worst_ratio = min(worst_ratio, max(gw, best_single) / opt)
print("fractional >= 0/1 optimum >= greedy-whole on 2000 instances:", ok)
print(f"worst ratio of max(greedy-whole, best single item) to the 0/1 optimum: {worst_ratio:.3f}")

print("the extreme case:", zero_one([1, 10], [2, 10], 10), "optimum, greedy-whole gets", greedy_whole([1, 10], [2, 10], 10))
the example: fractional 73/3, 0/1 optimum 23, greedy-whole 22
fractional >= 0/1 optimum >= greedy-whole on 2000 instances: True
worst ratio of max(greedy-whole, best single item) to the 0/1 optimum: 0.596
the extreme case: 10 optimum, greedy-whole gets 2

Two facts appear. First, the fractional optimum is always at least the 0/1 optimum, because every 0/1 solution is also a fractional one: the fractional problem is a relaxation of the 0/1 problem. Branch-and-bound solvers for 0/1 knapsack use exactly this greedy value as an upper bound to prune their search. Second, greedy with whole items can be arbitrarily bad on its own: in the extreme case, the tiny item with density 2 goes in first and blocks the big item, so greedy gets 2 when 10 was possible. Taking the better of greedy and the single most valuable item that fits never loses more than half, a 2-approximation, which the random test confirms (the worst ratio observed is above 0.50.5).

Proof sketch of the factor 2

Discard the items heavier than WW: no solution can use them, and greedy-whole skips them anyway. Now let item kk be the first item, in density order, that greedy-whole cannot fit (if there is none, greedy-whole took everything and is optimal). The items before it plus a fraction of item kk form the fractional optimum FF, so F≤(value of items before k)+vk≤greedy-whole+best single item≤2max⁡(greedy-whole,best single)F \le (\text{value of items before } k) + v_k \le \text{greedy-whole} + \text{best single item} \le 2 \max(\text{greedy-whole}, \text{best single}). Since OPT0/1≤F\mathrm{OPT}_{0/1} \le F, the better of the two is at least OPT0/1/2\mathrm{OPT}_{0/1} / 2.

In C++

The fractional greedy in C++, comparing densities by cross-multiplication to avoid floating-point ties.

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

struct Item { int w, v; };

double fractional_knapsack(std::vector<Item> items, int W) {
    std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
        return 1LL * a.v * b.w > 1LL * b.v * a.w;          // a.v/a.w > b.v/b.w
    });
    double total = 0;
    int room = W;
    for (const auto& it : items) {
        if (room == 0) break;
        int take = std::min(it.w, room);
        total += static_cast<double>(it.v) * take / it.w;
        room -= take;
    }
    return total;
}

int main() {
    std::printf("%.4f\n", fractional_knapsack({{4, 10}, {3, 7}, {2, 4}, {5, 12}}, 10));
    std::printf("%.4f\n", fractional_knapsack({{1, 2}, {10, 10}}, 10));
    std::printf("%.4f\n", fractional_knapsack({{6, 30}, {3, 14}, {4, 16}, {5, 15}}, 8));
}
24.3333
11.0000
39.3333

Test yourself

Items (weight, value): (2,6)(2, 6), (5,10)(5, 10), (4,10)(4, 10); capacity 7. What is the fractional optimum?

  1. 1616
  2. 1818
  3. 1919
  4. 2020

Why is the fractional optimum always at least the 0/1 optimum for the same items?

  1. Because greedy is optimal
  2. Because every 0/1 solution is a feasible fractional solution (all xi∈{0,1}x_i \in \{0, 1\})
  3. Because fractional items are lighter
  4. It is not; the 0/1 optimum can be larger

Which step of the fractional-knapsack exchange argument fails for 0/1 knapsack?

  1. Sorting by density
  2. Replacing δ\delta kilograms of a lower-density item by the same weight of the best item
  3. Using optimal substructure
  4. Computing the total value