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 have weights and values ; capacity . Choose fractions with maximising .
The natural measure is the value density , 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.
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 totalThe program uses the four items of the 0/1 knapsack lesson, with exact fractions.
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 , , and . Greedy takes all of item 1 and item 4 (9 kilograms, value 22), then one third of item 2 for the last kilogram: . 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 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 ), or it contains some amount of another item . Replace kilograms of item by kilograms of item 1 (as much as is still available). The weight is unchanged and the value changes by . Repeating this until item 1 is maxed out gives an optimal solution that makes the greedy choice.
Optimal substructure. After taking of item 1, what remains is a fractional knapsack with the other items and capacity , and an optimal solution of it plus the greedy choice is optimal overall (cut and paste). Induction finishes the proof.
The running time is for the sort. It can even be done in : 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 kilograms of item by item 1" is no longer allowed, because items come whole. Swapping all of item 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.
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 ).
Proof sketch of the factor 2
Discard the items heavier than : no solution can use them, and greedy-whole skips them anyway. Now let item 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 form the fractional optimum , so . Since , the better of the two is at least .
In C++
The fractional greedy in C++, comparing densities by cross-multiplication to avoid floating-point ties.
#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): , , ; capacity 7. What is the fractional optimum?
Why is the fractional optimum always at least the 0/1 optimum for the same items?
- Because greedy is optimal
- Because every 0/1 solution is a feasible fractional solution (all )
- Because fractional items are lighter
- It is not; the 0/1 optimum can be larger
Which step of the fractional-knapsack exchange argument fails for 0/1 knapsack?
- Sorting by density
- Replacing kilograms of a lower-density item by the same weight of the best item
- Using optimal substructure
- Computing the total value