Algorithmic patterns · 4 / 15 Theory

Greedy algorithms

A greedy algorithm builds the solution step by step, always choosing the best local option, without going back. It is very efficient, but only correct when it can be shown that this choice never spoils the global optimum.

# Activity selection: finish as soon as possible to leave room for the others
activities = [(1, 4), (3, 5), (0, 6), (5, 7), (8, 9)]       # (start, end)

chosen = []
last_end = -1
for start, end in sorted(activities, key=lambda a: a[1]):     # by end time
    if start >= last_end:
        chosen.append((start, end))
        last_end = end
print(chosen)                          # [(1, 4), (5, 7), (8, 9)]

# Change with "canonical" coins: always the largest possible
def greedy_change(amount, coins):
    result = []
    for m in sorted(coins, reverse=True):
        while amount >= m:
            amount -= m
            result.append(m)
    return result

print(greedy_change(63, [1, 5, 10, 25]))   # [25, 25, 10, 1, 1, 1]
print(greedy_change(6, [1, 3, 4]))         # [4, 1, 1]  but the optimum is [3, 3]!

Note the last example: with coins [1, 3, 4] the greedy gives [4, 1, 1] (3 coins) when [3, 3] (2 coins) is better. For that case you need dynamic programming, which you will see in its own lesson. With the usual coins (1, 5, 10, 25…) the greedy is optimal.

  • Typical strategy: sort by some criterion and walk once.
  • Activity selection: sort by end time; sorting by start or by duration would give wrong answers.
  • In the jump game it is enough to remember the farthest reachable position; there is no need to try all paths.

You practice it in Activity selection and Jump game.