← All questions
RareProgramming

Which problem has a standard greedy solution that first sorts the input?

Short answer
Fractional knapsack

Exercise

  1. Minimum spanning tree using Prim’s algorithm
  2. Fractional knapsack
  3. Travelling salesperson
  4. Shortest path using Dijkstra’s algorithm
  5. 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.

Greedy algorithms

Platforms

  • MAXIMUM

Download now and try it for free on your own tasks!

10 15 free credits • No credit card required
Version: Loading…

Choose the Windows app or the Chrome extension with phone controls.