Sub topic 3
Fractional Knapsack: When Greedy Is Optimal
This chapter assumes you can read Python functions that use sorted with a key, you know Big-O notation, and you know the knapsack problem statement from the first chapter. In the fractional variant you may take any fraction of an item, between 0 and 1. Taking a fraction gives you the same fraction of the item's value and weight. That one relaxation turns a hard problem into one that a simple greedy algorithm solves exactly.
The problem, stated precisely
You have n items. Item i has value v_i ≥ 0 and weight w_i > 0. You also have a capacity W ≥ 0. Choose a fraction x_i for each item, with 0 ≤ x_i ≤ 1, to maximise the total value Σ v_i · x_i while keeping the total weight Σ w_i · x_i ≤ W.
The quantity that drives everything is the value density (also called the ratio) r_i = v_i / w_i, the value you gain per unit of weight. Because items can be split, the capacity behaves like a supply of identical weight units. Each unit should go to whatever still earns the most per unit.
The greedy algorithm
- Sort items by
v_i / w_iin decreasing order. - Walk through the sorted list. Take each item whole while it fits.
- When an item does not fit, take the fraction that fills the remaining capacity exactly, then stop.
Here is the direct implementation:
def fractional_knapsack(items, capacity):
# items: list of (value, weight) with weight > 0
total = 0.0
for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
if capacity <= 0:
break
take = min(weight, capacity)
total += value * take / weight
capacity -= take
return total
print(fractional_knapsack([(60, 10), (100, 20), (120, 30)], 50)) # 240.0Tracing the example
| Item (value, weight) | Ratio | Capacity before | Taken | Value added | Running total |
|---|---|---|---|---|---|
| (60, 10) | 6 | 50 | 10 (all) | 60 | 60 |
| (100, 20) | 5 | 40 | 20 (all) | 100 | 160 |
| (120, 30) | 4 | 20 | 20 of 30 | 80 | 240 |
At most one item ends up split. Every item before it is taken whole and every item after it is left out. That structure holds in general, and the proof below relies on it.
Returning the fractions, not just the value
In practice you usually need the plan as well as the value. This version keeps the original item order in its output:
def fractional_knapsack_plan(items, capacity):
order = sorted(range(len(items)),
key=lambda i: items[i][0] / items[i][1],
reverse=True)
fractions = [0.0] * len(items)
total = 0.0
for i in order:
if capacity <= 0:
break
value, weight = items[i]
take = min(weight, capacity)
fractions[i] = take / weight
total += value * take / weight
capacity -= take
return total, fractions
print(fractional_knapsack_plan([(60, 10), (100, 20), (120, 30)], 50))
# (240.0, [1.0, 1.0, 0.6666666666666666])Why greedy is optimal: the exchange argument
Number the items so that r_1 ≥ r_2 ≥ … ≥ r_n. Let x be the greedy solution and let x* be any optimal solution. If the total weight of all items is at most W, greedy takes everything, which is clearly optimal. Otherwise greedy fills the knapsack exactly, and an optimal solution can also be assumed full: if it had spare room, adding more of any item with positive value would not decrease the total.
Suppose x* ≠ x. Let j be the first index where they differ. Greedy takes as much of item j as the remaining room allows, and the two solutions agree on items 1 … j−1. So x_j > x*_j. Both solutions use the same total weight, so x* must put some weight on a later item k > j that greedy does not. Move a small amount of weight δ in x* from item k to item j. The weight is unchanged and the value changes by
δ · r_j − δ · r_k = δ · (r_j − r_k) ≥ 0
because r_j ≥ r_k. The modified solution is still feasible and at least as good, so it is still optimal, and it agrees with greedy on more weight than before. Repeat the exchange until it equals x. Greedy therefore loses nothing compared with an optimal solution, so greedy is optimal.
The argument works only because δ can be arbitrarily small. If items cannot be split, you cannot shift "a little" weight, and the argument breaks. The next chapter builds the counterexample.
Complexity
Sorting dominates, so the running time is O(n log n) and the scan is O(n). Extra space is O(n) for the sorted copy. The running time does not depend on W at all. That is a sharp contrast with the 0/1 dynamic programs later in this tutorial.
A linear-time O(n) algorithm also exists. Find the split item with a median-of-ratios selection: pick the median ratio, check whether the items above it fit, and recurse into one half. Each step discards half the items, so the total work is linear. It rarely beats sorting in practice unless n is very large.
Common errors and edge cases
| Situation | What goes wrong | Fix |
|---|---|---|
| Sorting by value or by weight alone | Gives suboptimal answers, for example a heavy, valuable item crowds out denser ones | Sort by `value / weight` |
| Forgetting `reverse=True` | Takes the worst items first | Sort in descending order |
| An item with weight 0 | `ZeroDivisionError` in the sort key | Handle it separately: take it for free if its value is positive |
| An item with negative value | Greedy may add it once denser items run out | Filter out items with `v_i ≤ 0` first |
| `capacity == 0` or an empty list | Should return 0, which the code above does | Nothing to change, but test it |
| Ties in ratio | Any order among tied items is optimal | No special handling needed |
| Floating-point ratios | Two different ratios can round to the same float, and totals pick up rounding error | Use `fractions.Fraction` when exact answers matter |
An exact-arithmetic version needs only small changes:
from fractions import Fraction
def fractional_knapsack_exact(items, capacity):
total = Fraction(0)
capacity = Fraction(capacity)
for value, weight in sorted(items, key=lambda it: Fraction(it[0], it[1]), reverse=True):
if capacity <= 0:
break
take = min(Fraction(weight), capacity)
total += Fraction(value) * take / weight
capacity -= take
return total
print(fractional_knapsack_exact([(60, 10), (100, 20), (120, 30)], 50)) # 240Where this result is used later
The greedy value is never smaller than the 0/1 optimum for the same items, because every 0/1 solution is also a valid fractional solution. That makes it a cheap, safe upper bound. Branch and bound uses it to prune whole subtrees, and approximation arguments use it to sandwich the true optimum.
Exercise
Items are (value, weight) = (30, 5), (40, 10), (45, 15), (77, 22), (90, 25) and the capacity is 60. What does the greedy algorithm return, and which item is split?
Show answer
The ratios are 6, 4, 3, 3.5 and 3.6. In descending order: (30,5), (40,10), (90,25), (77,22), (45,15). Take 5 (total 30, room 55), then 10 (total 70, room 45), then 25 (total 160, room 20). Item (77,22) does not fit, so take 20/22 of it for 70. The answer is 230, and (77, 22) is the split item.
Exercise
In the exchange argument, why does it matter that the optimal solution x* can be assumed to fill the knapsack exactly?
Show answer
The argument needs x to put weight on some later item k whenever x_j > x_j. If x had spare capacity, it might simply leave that room unused, and no item k would exist to take weight from. Filling the free room with more of item j only raises the value when values are non-negative, so you can always assume x is full.
Exercise
Give a three-item instance where sorting by value alone (descending) is worse than sorting by ratio for the fractional problem.
Show answer
One example is capacity 10 with items (100, 100), (50, 5), (50, 5). Sorting by value takes 10/100 of the first item for 10. Sorting by ratio takes both small items for 100. Any instance where the most valuable item has a low density works the same way.