Algorithms · Greedy

Greedy algorithms

A greedy algorithm builds a solution one piece at a time, and at each step takes whatever looks best right now. It never looks ahead and never goes back to change an earlier choice. That makes greedy algorithms simple and fast. The hard part is knowing when "best right now" adds up to best overall.

The greedy idea

A greedy algorithm repeats one move:

  1. Look at the choices available right now.
  2. Pick the one that looks best by some simple rule: the biggest, the cheapest, the closest, the soonest.
  3. Commit to it, and go on to the smaller problem that is left.

Making change is the everyday example: to pay 63¢, take the biggest coin that fits (a quarter), then again (another quarter), then a dime, then three pennies. Six coins, which is the fewest possible.

But greedy can also walk straight past the best answer. In the tree on the right, the goal is a path from the top to the bottom with the largest sum. The greedy rule is "go to the larger child".

Press "Greedy step" to take the larger child, one level at a time.
Stop and think
Before you press anything: which path would you choose in the tree, and why does greedy not choose it?

7 → 3 → 99, for a sum of 109. Greedy compares only the two children in front of it: 12 beats 3, so it goes right and can never reach the 99 hiding below the 3. It finishes with 7 + 12 + 6 = 25. Every choice looked best at the moment it was made.

What would an algorithm need to do to be sure of finding the best path?

Look at the whole tree, not just the next level: for example, work out the best sum from each node to the bottom, starting at the leaves and moving up, then follow the best choices from the top. That is more work, but it never commits to a choice before knowing what lies below it.

When does greedy work?

A greedy algorithm gives the optimal answer when the problem has both of these properties:

Greedy choice propertyThere is always an optimal solution that starts with the greedy choice. So taking the choice that looks best now never rules out the best overall answer.This is the property the path tree lacks: going to 12 rules out 99.
Optimal substructureAn optimal solution to the whole problem contains optimal solutions to its subproblems. After the first choice, what is left is a smaller problem of the same kind, and solving it optimally finishes the job.Example: if the shortest route from A to C goes through B, its A-to-B part must be a shortest route from A to B.

Together they say: make the greedy choice, then solve what remains the same way, and the pieces add up to an optimal whole. Optimal substructure on its own is not enough. Many problems have it but not the greedy choice property, and those need dynamic programming, which tries every first choice and keeps the best.

To show a greedy algorithm is correct, the usual tool is an exchange argument: take any optimal solution that does not use the greedy choice, swap the greedy choice in, and show the result is no worse. To show it is wrong, one counterexample is enough.

Stop and think
Does the largest-sum path problem have optimal substructure?

Yes: the best path from the top contains the best path from whichever child it goes through. That is why the bottom-up method works. What it lacks is the greedy choice property: the best first step depends on numbers further down, so you cannot pick it by looking only at the children.

Greedy algorithms are usually very fast. Why?

Each step makes one choice and never undoes it, so the work is often just sorting the choices once (O(n log n)) and then a single pass. There is no searching through combinations.

The 0/1 knapsack problem

You have a knapsack that holds at most 25 units of space, and four items, each with a size and a value. You can take an item whole or leave it, but not part of it, and there is only one of each. Which items give the most value without going over 25?

Three greedy rules suggest themselves:

  • Largest value first. Take the laptop (12). Only 3 units of space are left, and nothing else fits. Total 12.
  • Smallest size first. Take the basketball (7), then the textbook (9). 9 units are left, and nothing else fits. Total 15.
  • Best value per unit of size first. Textbook (1.00), then PlayStation (0.90). The basketball no longer fits. Total 18.

The best possible is 18: the textbook and the PlayStation, using 19 units. So the ratio rule wins here. Does that mean it is the right rule? Try the "Camping trip" items in the lab below.

ItemSizeValueValue per size
Laptop22120.55
PlayStation1090.90
Textbook991.00
Basketball760.86

The fractional knapsack problem

Now suppose the items can be cut, like metal dust or grain: you can take any amount of each, up to what is available, and get value in proportion. The knapsack holds 50 kg.

Now the ratio rule is always optimal. Sort by value per kilogram and pour in the best material first:

  • all 3 kg of platinum: 300
  • all 3 kg of gold: 210
  • all 20 kg of silver: 600 (26 kg used)
  • 24 of the 30 kg of copper fill the bag: 240

Total: 1350, and the bag is exactly full. No other mix does better: any other mix uses some kilogram of a cheaper metal where a more valuable kilogram could have gone.

MetalAvailable (kg)Value per kgTotal value
Platinum3100300
Gold370210
Silver2030600
Copper3010300
Lead502100

Knapsack lab

Choose a problem, a greedy rule and a set of items, then run it. The C++ on the right steps along, and the result is compared with the best possible answer. For the 0/1 problem the lab finds that best answer by trying every combination of items; for the fractional problem the ratio rule gives it.

Problem
Greedy rule
Items

Items

The knapsack

Greedy
Best possible

What is happening

knapsack.cpp

    Stop and think
    Run the "Camping trip" items (capacity 50) as a 0/1 problem with the ratio rule. What goes wrong?

    The ratios are camera 6, tent 5, stove 4. Greedy takes the camera and the tent (30 kg, value 160), and then the stove (30 kg) no longer fits. The best is the tent and the stove: 50 kg, value 220. The camera looked best per kilogram, but taking it left 20 kg of space that no remaining item could use well.

    Now switch the same items to fractional. Why does the ratio rule win this time?

    After the camera and tent, greedy pours in 20 of the stove's 30 kg, worth 80, for 240 in total, with the bag exactly full. Leftover space is never wasted, because you can always take part of the next item. Every kilogram in the bag is the most valuable kilogram still available, which is the exchange argument in action.

    Which property fails for the 0/1 knapsack: the greedy choice property or optimal substructure?

    The greedy choice property. Optimal substructure still holds: if the best packing includes the tent, the rest of it must be the best packing of the other items into the remaining 30 kg. That is exactly what dynamic programming uses to solve the 0/1 knapsack, in O(n × capacity) time.

    Can you build a 0/1 example where "smallest size first" beats "best value per size"?

    Try capacity 10 with item A (size 6, value 7) and items B and C (size 5, value 5 each). The ratio rule takes A (ratio 1.17), and then nothing else fits: 7. Smallest first takes B and C: 10, which is optimal. No single greedy rule is right for every 0/1 instance.

    Coming next

    Greedy algorithms that are always optimal, and one that is not: making change with coins, scheduling the most activities in one room, Dijkstra's shortest paths, and Kruskal's minimum spanning tree.

    Huffman coding has its own page: a greedy algorithm that builds the best prefix code by always joining the two rarest letters.