Sub topic 5
Fractional knapsack by value-to-weight ratio
This chapter assumes you know Big-O notation, can sort a list in Python, and have read the previous chapters on the greedy-choice property and the exchange argument. It uses both ideas.
The problem
You have a knapsack with capacity W and n items. Item i has a value vi and a positive weight wi. In the fractional version you may take any fraction xi between 0 and 1 of each item. You want to maximize the total value, the sum of xi · vi, subject to the sum of xi · w_i being at most W.
Think of gold dust, flour, or fuel. You can scoop part of an item, so the choice for each item is a continuous amount, not yes or no.
The greedy rule
Compute the ratio vi / wi for each item. This is the value you get per unit of capacity. Then:
- Sort the items by ratio, highest first.
- Take each item whole while it fits.
- When the next item does not fit, take the fraction that fills the remaining capacity, and stop.
Implementation
def fractional_knapsack(items, capacity):
"""items is a list of (value, weight) pairs with weight > 0."""
total = 0.0
ranked = sorted(items, key=lambda it: it[0] / it[1], reverse=True)
for value, weight in ranked:
if capacity == 0:
break
take = min(weight, capacity) # whole item, or what still fits
total += value * take / weight # value scales linearly with weight
capacity -= take
return total
print(fractional_knapsack([(60, 10), (100, 20), (120, 30)], 50)) # 240.0Worked trace
Capacity is 50. The items are (value, weight) pairs.
| Item | Value | Weight | Ratio | Action | Remaining capacity | Total value |
|---|---|---|---|---|---|---|
| A | 60 | 10 | 6 | take all | 40 | 60 |
| B | 100 | 20 | 5 | take all | 20 | 160 |
| C | 120 | 30 | 4 | take 20/30 | 0 | 240 |
The answer is 240. The same items under the 0/1 rule give only 220, because the best choice is B and C, with weights 20 and 30. The fractional version gets more because it can split C.
Why the greedy choice is safe
Use an exchange argument. Let item g have the highest ratio. Suppose an optimal solution uses less of g than it could, meaning xg is below 1 and the knapsack is full. Then the solution holds some weight of a lower-ratio item j. Swap a small weight d of item j for the same weight d of item g. The capacity used does not change. The value changes by d · (vg/wg − vj/w_j), which is at least 0. So the new solution is no worse, and some optimal solution takes as much of the best-ratio item as possible. The remaining problem has the same form with smaller capacity, which gives optimal substructure. Induction finishes the proof.
The swap needs to move an arbitrary amount of weight. That is exactly what fractions allow.
Complexity
- Sorting costs O(n log n). The loop afterwards is O(n).
- Total time is O(n log n). Space is O(n) for the sorted copy, or O(1) extra if you sort in place.
- A linear-time O(n) version exists. It uses weighted-median selection to find the cut-off ratio without a full sort. GATE questions almost always expect O(n log n).
Edge cases and common errors
- Total weight at most W. The loop takes every item, and no fractions appear.
- At most one item is fractional. The greedy loop splits only the item where capacity runs out. Every earlier item is whole and every later item is untouched. This is a quick sanity check on a hand trace.
- Ties in ratio. Any order among tied items gives the same optimal value, though the chosen amounts may differ.
- Zero weight. A zero-weight item with positive value would divide by zero. The problem statement assumes positive weights.
- Sorting by value or by weight alone. Both fail. Sorting by value takes a heavy valuable item first. Sorting by weight takes light items even when their value is poor. Only the ratio is correct.
Relation to other problems
Fractional knapsack is the cleanest example of a greedy algorithm whose correctness depends on divisibility. It is also the standard contrast case in GATE questions. The fractional version is solved greedily in O(n log n). The 0/1 version needs a table and takes O(nW) time.
Exercise
Capacity is 10. The items as (value, weight) are A = (30, 5), B = (40, 10) and C = (20, 4). What is the maximum value for the fractional knapsack, and what is the best value for the 0/1 knapsack?
Show answer
Ratios are A = 6, B = 4, C = 5, so the order is A, C, B. Take A whole (weight 5, value 30), then C whole (weight 4, value 20). One unit of capacity remains, so take 1/10 of B for a value of 4. The fractional maximum is 54. For 0/1, A and C together weigh 9 and give 50, and B alone gives 40, so the best 0/1 value is 50.
Exercise
What is the time complexity of the greedy fractional knapsack algorithm for n items, and which step dominates?
Show answer
O(n log n). Sorting by ratio dominates. The single pass that fills the knapsack is O(n).