Start free

Beyond A level · 5 exercises

Python greedy algorithms

Take the best-looking choice at each step and never go back: sorting first usually makes the best choice obvious.

It works only when a local best choice can't spoil the whole answer; for meetings, choosing the one that ends earliest leaves the most room.

meetings = [(1, 4), (3, 5), (0, 6), (5, 7)]
end, count = -1, 0
for s, e in sorted(meetings, key=lambda m: m[1]):
    if s >= end:
        count += 1
        end = e
print(count)

Watch for: Sorting by the wrong thing (start instead of end) gives a plausible but wrong answer: try a small case by hand.

Exercises

  1. Most meetingsOne room, many meetings with start and end times.Expert
  2. Rooms neededGiven meetings with start and end times, how many rooms are needed so that noneExpert
  3. Fewest jumpsEach number says how far you may jump forward from that position.Expert
  4. Fractional knapsackItems can be cut, so you may take part of one.Expert
  5. Joining ropesJoining two ropes costs the sum of their lengths.Expert
Start with “Most meetings”