Greedy
For each one, name the greedy choice and convince yourself it is safe before coding. Then it is usually a sort and one pass.
The lesson is Greedy.
Platforms needed
arrivals and departures list, for each train, when it arrives and when it leaves; a
platform freed at time t cannot be reused by a train arriving at t. Write
min_platforms(arrivals, departures) that returns the fewest platforms so no train waits.
min_platforms([900, 940, 950, 1100, 1500, 1800], [910, 1200, 1120, 1130, 1900, 2000]) -> 3
min_platforms([100], [200]) -> 1
The point is to practise the "sort events and sweep" technique: the answer is the maximum number of trains present at once.
def min_platforms(arrivals, departures):
...
Boats to carry everyone
weights lists people's weights; each boat carries at most two people and at most limit
total weight, and nobody weighs more than limit. Write boats(weights, limit) that
returns the fewest boats.
boats([1, 2], 3) -> 1
boats([3, 2, 2, 1], 3) -> 3
boats([3, 5, 3, 4], 5) -> 4
The point is to practise the pairing greedy: the heaviest person goes with the lightest if they fit, otherwise alone.
def boats(weights, limit):
...
Where to start the loop
Driving a circular route, station i provides gas[i] fuel and it costs cost[i] to
reach the next station. Starting with an empty tank at some station, write
start_station(gas, cost) that returns the index you must start from to complete the
loop, or -1 if impossible. If a solution exists it is unique.
start_station([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) -> 3
start_station([2, 3, 4], [3, 4, 3]) -> -1
The point is to practise a one-pass greedy: when the tank goes negative, nothing before this point can be the start.
def start_station(gas, cost):
...
Fewest jumps to the end
Each position in jumps says how far you can jump forward from it, and the end is always
reachable. Write min_jumps(jumps) that returns the fewest jumps to get from index 0 to
the last index.
min_jumps([2, 3, 1, 1, 4]) -> 2
min_jumps([1, 1, 1]) -> 2
min_jumps([5]) -> 0
The point is to practise greedy in layers: everything reachable with j jumps forms a
range, and the next range is the furthest any of those positions can reach.
def min_jumps(jumps):
...
Sweets by rating
Children stand in a line with ratings. Each child gets at least one sweet, and any child
with a higher rating than a neighbour must get more sweets than that neighbour. Write
min_sweets(ratings) that returns the fewest sweets in total.
min_sweets([1, 0, 2]) -> 5 (2, 1, 2)
min_sweets([1, 2, 2]) -> 4 (1, 2, 1)
min_sweets([5]) -> 1
The point is to practise a two-pass greedy: satisfy the left neighbours going right, then the right neighbours going left, taking the max.
def min_sweets(ratings):
...
Fewest removals to end overlaps
intervals is a list of (start, end) pairs; two touching at an endpoint do not overlap.
Write min_removals(intervals) that returns the fewest intervals to remove so none of
the remaining ones overlap.
min_removals([(1, 2), (2, 3), (3, 4), (1, 3)]) -> 1
min_removals([(1, 2), (1, 2), (1, 2)]) -> 2
min_removals([(1, 2), (2, 3)]) -> 0
The point is to practise seeing a problem as the complement of one you know: keep the most non-overlapping intervals (earliest end first), remove the rest.
def min_removals(intervals):
...
Cut into self-contained pieces
Write partition_sizes(text) that cuts text into as many pieces as possible such that
each letter appears in only one piece, and returns the piece lengths in order.
partition_sizes("ababcbacadefegdehijhklij") -> [9, 7, 8]
partition_sizes("abc") -> [1, 1, 1]
partition_sizes("aaa") -> [3]
The point is to practise a greedy that extends the current piece to the last occurrence of every letter it contains.
def partition_sizes(text):
...
Making change at the stand
Each drink costs 5. Customers pay with a 5, 10 or 20 note, in the order given in bills,
and you start with no money. Write can_serve_all(bills) that returns whether you can
give every customer correct change.
can_serve_all([5, 5, 5, 10, 20]) -> True
can_serve_all([5, 5, 10, 10, 20]) -> False
can_serve_all([10]) -> False
The point is to practise a greedy choice when breaking a 20: prefer giving a 10 and a 5 over three 5s, because 5s are more useful later.
def can_serve_all(bills):
...
Load the truck
boxes is a list of (count, units_per_box) and the truck holds at most capacity boxes.
Write max_units(boxes, capacity) that returns the most units you can load.
max_units([(1, 3), (2, 2), (3, 1)], 4) -> 8 (1x3 + 2x2 + 1x1)
max_units([(5, 10)], 2) -> 20
The point is to practise the simplest greedy: sort by value and take as much as fits.
def max_units(boxes, capacity):
...
Cheapest way to send people to two cities
costs is a list of (cost_a, cost_b) for 2n people: what it costs to send each to
city A or city B. Exactly n must go to each. Write min_total(costs) that returns the
smallest total cost.
min_total([(10, 20), (30, 200), (400, 50), (30, 20)]) -> 110
min_total([(5, 1), (1, 5)]) -> 2
The point is to practise a greedy on the difference: send everyone to A, then switch
the n people for whom switching to B saves the most.
def min_total(costs):
...
Next: Dynamic programming.