Sub topic 3
Fractional Knapsack by Value-to-Weight Ratio
Prerequisites and problem model
Assume you know asymptotic notation, sorting, and basic greedy algorithms. The fractional knapsack problem gives items with weights and values. A knapsack has a maximum capacity. You may take an entire item or any fraction of it.
The goal is to maximize total value without exceeding the capacity. For an item with value \(v\) and weight \(w\), define its value density as:
\[ \text{density} = \frac{v}{w} \]
A greedy strategy takes available items in decreasing order of density.
Greedy algorithm
- Compute each item's value-to-weight ratio.
- Sort items by decreasing ratio.
- Take each item completely if it fits.
- Otherwise, take the fraction that fills the remaining capacity and stop.
def fractional_knapsack(items, capacity):
# Each item is a (weight, value) pair.
ordered = sorted(items, key=lambda item: item[1] / item[0],
reverse=True)
total_value = 0.0
remaining = capacity
for weight, value in ordered:
if remaining == 0:
break
amount = min(weight, remaining)
total_value += amount * (value / weight)
remaining -= amount
return total_value
items = [(10, 60), (20, 100), (30, 120)]
print(fractional_knapsack(items, 50)) # 240.0The densities are 6, 5, and 4. The algorithm takes the first two items and \(20\) units of the third item. The result is:
\[ 60 + 100 + 20 \cdot 4 = 240 \]
Why the ratio rule works
Suppose a solution contains some positive amount of an item with density \(d1\), while a higher-density item with density \(d2 > d_1\) is not fully used. Replace a small weight amount from the lower-density item with the same weight amount from the higher-density item.
The total weight stays unchanged. The value increases by:
\[ \Delta w(d2-d1) > 0 \]
Therefore, an optimal solution cannot use a lower-density item while leaving available capacity for a higher-density item. Repeating this exchange produces the greedy solution. This is an exchange argument, a proof technique that transforms an optimal solution into the algorithm's solution without reducing its quality.
Complexity and common errors
| Operation | Cost |
|---|---|
| Sorting by density | \(O(n \log n)\) |
| Scanning the sorted items | \(O(n)\) |
| Total | \(O(n \log n)\) |
Common errors include sorting by value instead of density, forgetting that only the final item may be fractional, and treating zero-weight items as ordinary items. A positive-value, zero-weight item should be included immediately because it consumes no capacity.
Exercise
Items have weights and values (5, 30), (10, 40), and (20, 100), with capacity 17. Which amounts should the greedy algorithm take, and what is the maximum value?
Show answer
The densities are 6, 4, and 5. Take (5, 30), then (20, 100) fractionally for 12 of its 20 weight. The maximum value is 30 + 60 = 90.