Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

What Is a Greedy Algorithm? Two Worked Python Examples

See why greedy choices work for minimum waiting time and tandem bicycle pairing, and use a coin example to recognize when they fail.

Table of Contents

A greedy algorithm makes the best available choice under a stated rule, commits to it, and moves on. Greedy methods can be fast and simple. To know whether one finds the best overall answer, show that its choices can be part of an optimal solution.

Introducing the greedy algorithm Picture 1

Example 1: Minimize total waiting time

If every job is ready at the start and one machine runs each job to completion, schedule shorter jobs first. For durations of 3, 1, and 2 minutes, running them as 1, 2, 3 gives waits of 0, 1, and 3 minutes, for a total of 4.

def minimum_waiting_time(durations):
    total_wait = 0
    elapsed = 0
    for duration in sorted(durations):
        total_wait += elapsed
        elapsed += duration
    return total_wait


assert minimum_waiting_time([3, 1, 2]) == 4
Introducing the greedy algorithm Picture 2
Each job’s duration contributes to the waiting time of the jobs that follow it.

Why it works: If a longer job sits immediately before a shorter one, swapping them reduces the shorter job’s wait by more than it adds to the longer job’s wait. Later jobs still wait for both. Repeat the swap wherever needed until the durations are in ascending order.

Example 2: Maximize the sum of tandem bicycle speeds

Pair one rider from each team. If the faster rider determines the pair’s speed, sort one team fastest first and the other slowest first. For red speeds [2, 5, 8] and blue speeds [1, 6, 9], the resulting pair speeds are 9, 6, and 8, for a total of 23.

def max_tandem_speed(red, blue):
    if len(red) != len(blue):
        raise ValueError('Teams must have the same size')
    pairs = zip(sorted(red), sorted(blue, reverse=True))
    return sum(max(a, b) for a, b in pairs)


assert max_tandem_speed([2, 5, 8], [1, 6, 9]) == 23

Among all riders, take the fastest half, breaking ties consistently with the sorted pair order. If that half contains r red and b blue riders, there are exactly r slower blue and b slower red riders. Pairing opposite ends puts one rider from the fastest half in each pair. Their sum is an upper bound for any pairing, and this pairing reaches it.

Check where a greedy rule fails

With coin values 1, 3, and 4, choosing the largest coin first for a total of 6 gives 4 + 1 + 1. Two 3s use fewer coins. Test a greedy rule on small examples with known optimal answers and look for a proof before relying on it. Both Python examples above take O(n log n) time and O(n) extra space because sorted() creates copies. See sorting and algorithm trade-offs for more practice.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.