Sub topic 9
Fractional Knapsack: Best Value per Weight
This chapter assumes you can read Python with sorted and lambda, know that sorting costs O(n log n), and have read the earlier chapter on the exchange argument. The fractional knapsack is the clearest place to see that argument at work. It also sets up a contrast with dynamic programming that comes back later in the tutorial.
The Problem
You have a knapsack that holds at most W units of weight. There are n items, and item i has a value v_i and a weight w_i. You may take any fraction x_i of an item, with 0 ≤ x_i ≤ 1, and you get x_i · v_i value for x_i · w_i weight. The goal is to maximize total value while keeping total weight at or below W.
Think of the items as bulk goods: gold dust, flour, spices. Splitting them costs nothing, so a partial scoop is worth exactly its share of the whole.
The key quantity is the value density, or ratio, r_i = v_i / w_i. This is the value you gain per unit of capacity spent.
The Greedy Rule
Sort the items by ratio, highest first. Take each item whole while it fits. When the next item doesn't fit, take the fraction of it that fills the remaining capacity, then stop.
Here is the direct implementation:
def fractional_knapsack(items, capacity):
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.0Trace the example. The ratios are 6, 5 and 4. Greedy takes all of item 1 (weight 10, value 60) and all of item 2 (weight 20, value 100), which leaves 20 units of capacity. It then takes 20/30 of item 3 for 80 more value. The total is 240.
The running time is O(n log n) for the sort plus O(n) for the scan.
Why It Is Optimal: The Exchange Argument
Number the items so that r_1 ≥ r_2 ≥ … ≥ r_n. Let G = (g_1, …, g_n) be the greedy fractions and let O = (o_1, …, o_n) be any optimal solution. Assume all values are positive and that the total weight of all items exceeds W. If it doesn't, greedy takes everything, which is trivially optimal.
Greedy fills the knapsack exactly, and you can assume O does too. If O left capacity unused, adding more of any unfinished item would raise its value, so O would not be optimal.
Suppose O ≠ G. Let i be the first index where they differ. Greedy takes as much of each item as it can in ratio order, so o_i < g_i. Both solutions use the same total weight, so there must be some later item j > i with o_j > g_j, which means o_j > 0.
Now exchange weight. Move δ = min((g_i − o_i)·w_i, (o_j − g_j)·w_j) units of weight from item j to item i in O. The total weight stays the same. The value changes by
δ · r_i − δ · r_j = δ · (r_i − r_j) ≥ 0,
because r_i ≥ r_j. The modified solution is still feasible and at least as good, so it is still optimal. It also agrees with G on one more coordinate, or moves strictly closer to agreeing on coordinate i. Each exchange either closes the gap at i completely or empties item j's excess, so finitely many exchanges turn O into G without ever losing value. Therefore G is optimal.
The 0/1 Version Breaks Greedy
In the 0/1 knapsack, each x_i must be 0 or 1. Run the ratio rule on the same data with W = 50:
| Strategy | Items taken | Weight | Value |
|---|---|---|---|
| Greedy by ratio (0/1) | items 1, 2 | 30 | 160 |
| Optimal (0/1) | items 2, 3 | 50 | 220 |
| Greedy (fractional) | items 1, 2, 2/3 of item 3 | 50 | 240 |
Greedy grabs the densest item first, and its leftover 20 units can't hold item 3. The exchange argument fails because you can't move a small δ of weight between items. Swapping whole items changes the total weight, and that can break feasibility or leave capacity stranded.
Two lessons come from this table:
- The fractional optimum (240) is an upper bound on the 0/1 optimum (220). Branch-and-bound solvers for 0/1 knapsack use exactly this fractional bound to prune their search.
- The 0/1 problem is NP-hard. It needs dynamic programming, which is pseudo-polynomial at O(nW), or approximation. The chapter "Greedy or Dynamic Programming?" returns to this pair.
Common Errors and Edge Cases
The short version above is fine for clean inputs. Real inputs break it in several ways:
- Zero-weight items.
value / weightraisesZeroDivisionError. An item with zero weight and positive value is free, so take it whole. - Non-positive values. An item with value ≤ 0 should never be taken. After sorting by ratio, every such item sits at the end, so you can stop when you reach one.
- Floating-point drift. Repeated
capacity -= takewith floats can leave something like1e-15of capacity, or report a fraction like0.6666666666666666. If you need exact answers, usefractions.Fraction. - Ties in ratio. Their order doesn't matter. Any order among equal-ratio items gives the same total value, though the chosen fractions can differ.
- Returning only the value. Callers usually need to know how much of each item to take.
This version handles all of these and returns the plan:
from fractions import Fraction
def fractional_knapsack_plan(items, capacity):
"""items: list of (value, weight) with integer values and weights.
Returns (total_value, fractions) using exact arithmetic."""
if capacity < 0:
raise ValueError("capacity must be non-negative")
fractions = [Fraction(0)] * len(items)
total = Fraction(0)
remaining = Fraction(capacity)
# Free items: zero weight, positive value.
for i, (value, weight) in enumerate(items):
if weight < 0:
raise ValueError("weights must be non-negative")
if weight == 0 and value > 0:
fractions[i] = Fraction(1)
total += value
order = [i for i, (_, w) in enumerate(items) if w > 0]
order.sort(key=lambda i: Fraction(items[i][0], items[i][1]), reverse=True)
for i in order:
value, weight = items[i]
if remaining == 0 or value <= 0:
break
take = min(Fraction(weight), remaining)
fractions[i] = take / weight
total += value * take / weight
remaining -= take
return total, fractions
total, fractions = fractional_knapsack_plan([(60, 10), (100, 20), (120, 30)], 50)
print(total) # 240
print([str(f) for f in fractions]) # ['1', '1', '2/3']
print(fractional_knapsack_plan([(5, 0), (-3, 1), (10, 4)], 2))
# (Fraction(10, 1), [Fraction(1, 1), Fraction(0, 1), Fraction(1, 2)])Fraction(a, b) requires rational arguments such as int values. If your inputs are floats, convert them first with Fraction(str(x)) to avoid inheriting binary rounding.
Doing Better Than Sorting
A full sort is more than the problem needs. Only one item is ever split. Call it the critical item. Every item with a higher ratio is taken whole, and every item with a lower ratio is left out. You can find the critical item in expected O(n) time with a quickselect-style search:
- Pick a pivot ratio and partition the items into higher, equal and lower groups.
- If the total weight of the higher group already exceeds the remaining capacity, recurse into the higher group.
- Otherwise take the whole higher group, subtract its weight, then handle the equal group, and recurse into the lower group if capacity remains.
Each call discards a constant fraction of the items on average, so the total work is linear. Using median-of-medians pivots makes it worst-case O(n). In practice the O(n log n) sort is simpler and fast enough unless n is very large or the problem sits inside a hot loop, such as computing bounds in branch-and-bound.
Where It Shows Up
- Bounds for 0/1 knapsack. The LP relaxation of 0/1 knapsack is exactly the fractional problem, so the greedy answer gives the bound.
- Resource allocation with divisible resources. Examples include bandwidth, budget split across ad channels with linear returns, and blending raw materials.
- Portfolio-style "fill the cheapest per unit first" logic. Any problem with linear returns and a single capacity constraint reduces to sorting by ratio.
The greedy rule stops being optimal once returns are nonlinear (diminishing returns per item) or there is more than one capacity constraint (weight and volume). Those cases need linear programming or other methods.
Exercise
Items are (value, weight) = (30, 5), (40, 10), (45, 15), (77, 22), (90, 25), with capacity 60. What is the optimal fractional knapsack value, and which item is split?
Show answer
The ratios are 6, 4, 3, 3.5 and 3.6. In descending order: (30,5) ratio 6, (40,10) ratio 4, (90,25) ratio 3.6, (77,22) ratio 3.5, (45,15) ratio 3. Take the first three whole: weight 40, value 160. The remaining capacity is 20, so take 20/22 of (77,22) for 70 more value. The total is 230, and the split item is (77, 22).
Exercise
Someone proposes sorting by value (highest first) instead of by ratio. Give a fractional knapsack instance where this is worse than sorting by ratio.
Show answer
Use capacity 10 and items (10, 10) and (9, 1). By value, greedy takes all of (10,10) and gets 10. By ratio, it takes (9,1) first for 9, then 9/10 of (10,10) for 9 more, which totals 18.
Exercise
In the exchange proof, why must there be an item j > i with oj > gj once you know oi < gi?
Show answer
Greedy and the optimal solution both fill the knapsack exactly, so they use the same total weight. They agree on items 1 through i−1, and O uses less weight than G on item i. That missing weight has to be used somewhere after i, so some j > i has oj > gj.
Exercise
Show that the fractional optimum is always at least the 0/1 optimum, and give an instance where the two are equal.
Show answer
Every 0/1 solution is also a valid fractional solution with each x_i equal to 0 or 1, so the fractional maximum can't be smaller. They are equal whenever greedy's knapsack fills with no split item. For example, items (60,10) and (100,20) with capacity 30 give 160 in both versions.