TExcelTAD
Home › Data Structures & Algorithms › Greedy Algorithms

Greedy Algorithms

A greedy algorithm builds a solution step by step, always making the choice that looks best right now, and never reconsidering it. Greedy algorithms are usually simple and fast. The catch: the locally best choice is not always globally best, so a greedy algorithm is only correct when you can prove its choices are safe.

You have already met several correct greedy algorithms:

Algorithm Greedy choice
Dijkstra finish the closest unfinished vertex
Prim / Kruskal add the cheapest safe edge
Huffman coding merge the two lightest trees

And some cases where greedy fails: the 0/1 knapsack (best value per kg), coin change with coins [1, 4, 6], and nearest-neighbour TSP.

Example 1: making change (when greedy works)

With the euro coin system (in cents: 200, 100, 50, 20, 10, 5, 2, 1), "always take the largest coin that fits" gives the fewest coins:

python · try it yourself
def greedy_change(amount, coins):
    used = []
    for c in sorted(coins, reverse=True):
        while amount >= c:
            amount -= c
            used.append(c)
    return used

euro = [200, 100, 50, 20, 10, 5, 2, 1]
print(greedy_change(289, euro))
print(len(greedy_change(289, euro)), "coins")

odd = [1, 4, 6]
print("coins [1, 4, 6], amount 8:", greedy_change(8, odd), "but 4 + 4 uses only 2 coins")
[200, 50, 20, 10, 5, 2, 2]
7 coins
coins [1, 4, 6], amount 8: [6, 1, 1] but 4 + 4 uses only 2 coins

Coin systems for which greedy is always optimal are called canonical. Real currencies are designed that way; arbitrary coin sets are not, and then you need dynamic programming.

Example 2: activity selection

A meeting room receives requests with start and end times. What is the largest number of meetings that don't overlap? The greedy choice that works: always pick the meeting that ends first among those that start after the last chosen one ends. It leaves as much time as possible for the rest.

python · try it yourself
meetings = [("standup", 9, 10), ("design", 9, 12), ("review", 10, 11), ("lunch", 12, 13),
            ("1:1", 11, 12), ("planning", 10, 13), ("demo", 13, 15), ("retro", 14, 15)]

def select(meetings):
    chosen, free_from = [], 0
    for name, start, end in sorted(meetings, key=lambda m: m[2]):    # earliest end first
        if start >= free_from:
            chosen.append(name)
            free_from = end
            print(f"take {name:<8} {start:>2}-{end:<2}")
    return chosen

print(len(select(meetings)), "meetings")
take standup   9-10
take review   10-11
take 1:1      11-12
take lunch    12-13
take demo     13-15
5 meetings

Other "obvious" rules fail. Choosing the shortest meeting first, or the one that starts first, can block better combinations:

python · try it yourself
meetings = [("A", 0, 10), ("B", 1, 3), ("C", 4, 6), ("D", 7, 9)]

def greedy(meetings, key):
    chosen, free_from = [], 0
    for name, start, end in sorted(meetings, key=key):
        if start >= free_from:
            chosen.append(name)
            free_from = end
    return chosen

print("earliest start:", greedy(meetings, key=lambda m: m[1]))
print("earliest end:  ", greedy(meetings, key=lambda m: m[2]))
earliest start: ['A']
earliest end:   ['B', 'C', 'D']

Starting with the long meeting A (it starts first) blocks the other three.

Example 3: fractional knapsack

If items can be cut (gold dust, liquids, time), the greedy rule "take the highest value per kilogram first" is optimal: you fill the bag with the most valuable material and cut the last item to fit.

python · try it yourself
items = [("saffron", 2, 60), ("vanilla", 5, 75), ("pepper", 8, 40)]   # name, kg, value
capacity = 10

total, room = 0.0, capacity
for name, kg, value in sorted(items, key=lambda it: it[2] / it[1], reverse=True):
    take = min(kg, room)
    total += value * take / kg
    room -= take
    print(f"take {take} kg of {name} ({value / kg:.0f}/kg)")
    if room == 0:
        break
print("total value:", total)
take 2 kg of saffron (30/kg)
take 5 kg of vanilla (15/kg)
take 3 kg of pepper (5/kg)
total value: 150.0

Compare that with the 0/1 knapsack lesson, where the same rule failed because items could not be cut.

How do you know greedy is right?

Two properties together guarantee a correct greedy algorithm:

  1. Greedy-choice property: some optimal solution starts with the greedy choice. Usually proven by an exchange argument: take any optimal solution, swap its first choice for the greedy one, and show it doesn't get worse.
  2. Optimal substructure: after the greedy choice, the remaining problem is a smaller instance of the same problem.

For activity selection: if an optimal schedule starts with some meeting X, replacing X with the meeting that ends earliest can't create an overlap (it ends no later than X), so the schedule stays optimal.

Greedy vs dynamic programming

Greedy Dynamic programming
Choices one, never revisited all, best kept
Speed often O(n log n) (a sort + one pass) number of states × choices
Correctness only with a proof whenever the recurrence is right
Use when the greedy choice is provably safe greedy fails or you aren't sure

Tip: When designing a greedy algorithm, try to break it with a small counterexample before trusting it. If you find one, switch to dynamic programming.

Test yourself

What characterises a greedy algorithm?

  1. It tries every possibility
  2. It makes the locally best choice at each step and never undoes it
  3. It always uses recursion
  4. It sorts the input twice

For activity selection, which greedy rule is optimal?

  1. Shortest activity first
  2. Earliest start first
  3. Earliest end first
  4. Latest start first

For which knapsack variant is "best value per kg first" optimal?

  1. 0/1 knapsack
  2. Fractional knapsack
  3. Both
  4. Neither