RareProgramming
Which problem has a standard greedy solution that first sorts the input?
Short answer
Fractional knapsack
Exercise
- Minimum spanning tree using Prim’s algorithm
- Fractional knapsack
- Travelling salesperson
- Shortest path using Dijkstra’s algorithm
- Maximum flow
Solution
Take items in descending order of value per unit weight, using a fraction of the last item if needed.
Compare value per unit weight. Suppose a five-kilogram bag is available, and items weighing three and four kilograms have values nine and eight. Take all of the first item, then fill the remaining two kilograms with half of the second.
W = 5 kg. A: 9 / (3 kg) = 3/kg; B: 8 / (4 kg) = 2/kg. 3 kg + 2 kg = 5 kg. 9 + (2/4) × 8 = 13.
Why sorting works: exchanging a kilogram of lower-value material for one of higher value costs no extra weight and cannot reduce the return. This exchange relies on divisibility and does not establish the rule for indivisible items.
Platforms
- MAXIMUM
