Three problems where the options change as you go. The move: keep the allowed options in a heap, and act on the best one, or give back the worst, only when you must.
You work on an ad platform, an electric car app and a compute cluster. The three problems on this street come from all three. In each, the choices you may make change as you move, and you must pick well.
What opens up, and when you may act, changes from problem to problem. Here is each rule.
| Problem | The options that are allowed | The one you take | When you take it |
|---|---|---|---|
| Fewest campaigns to reach a revenue target | campaigns the budget can start | the largest gain | at once, before each run |
| Minimum refuel stops | stations already passed | the largest charge | late, only when the next point is out of reach |
| Maximum performance of a team | servers of at least the current quality | the k fastest | every step, giving back the slowest |
The structure is the same each time. A sort makes the options open in order. A heap keeps the allowed ones, and returns the best in a logarithmic step.
Exercise · Predict the output: How many campaigns reach the target?. Each round the code runs the affordable campaign with the largest gain. A scan finds it here, where a heap would do the same job faster. What does it print?
costs = [1, 3, 5, 8, 11]
gains = [2, 4, 6, 9, 3]
budget = 2
target = 20
used = [False] * len(costs)
count = 0
while budget < target:
best = -1
for i in range(len(costs)):
if not used[i] and costs[i] <= budget and (best == -1 or gains[i] > gains[best]):
best = i
if best == -1:
break
used[best] = True
budget += gains[best]
count += 1
print(count)Before you code, name three things. What makes an option allowed, what order do options open in, and what makes one allowed option better than another?
Sort the options by the order in which they open. As each one opens, push it into the heap. When you must act, take the best from the heap. If the heap is empty and you must act, the answer is -1.
The heap holds exactly the options that are allowed now. The best of them is never worse than another allowed option, because swapping the other for it leaves every later step at least as well off.
The campaigns problem is the plain case. With a budget of 3 and the costs 2, 5, 4, 9, 12 and gains 3, 6, 2, 10, 8, three campaigns reach a target of 20, and two reach 12. Running the cheapest campaign first needs 4 for a target of 20, because it spends the budget on small gains.
Run the affordable campaign with the largest gain each round: with a budget of 3 and a target of 20, three campaigns do it.
Exercise · Find the bug: The cheapest campaign first. This finds the fewest campaigns that bring the budget to the target, or -1. It picks which affordable campaign to run each round. It is wrong on some inputs. Which line is wrong?
def fewest_campaigns(target, budget, costs, gains):
n = len(costs)
used = [False] * n
count = 0
while budget < target:
best = -1
for i in range(n):
if not used[i] and costs[i] <= budget:
if best == -1 or costs[i] < costs[best]:
best = i
if best == -1:
return -1
used[best] = True
budget += gains[best]
count += 1
return countThe Academy lesson Greedy with a heap keeps the options in a heap and gives one back when there are too many. Sort, then choose shows how a sort makes the options open in order. This street does not teach those again. It adds three things.
The decision can be late. The refuel problem never decides at a station. It passes every station, pushes its charge into the heap, and acts only when the next point is out of reach. Then it takes the largest charge in the heap and counts one stop.
Take a target of 30, a start charge of 8 and the stations [4,6] [7,3] [12,10] [18,5] [23,9]. The stops are the charges 6, 10 and 9, so the answer is 3. Taking the most recent passed station instead needs 4.
Stopping at the most recent passed station needs 4 stops where the largest charge needs 3, on the same road.
The sort and the heap use different keys. The team problem sorts by quality, from high to low, so the newest server sets the quality floor. The heap orders by speed, so the slowest is on top. When the group has more than k servers, give back the slowest.
For speeds 2, 10, 3, 1, 9, qualities 5, 4, 3, 9, 2 and k of 3, the best score is 52. Choosing the k fastest servers regardless of quality gives 44.
Exercise · Break it: The k fastest servers. This returns the best throughput of a group of exactly k servers by taking the k fastest. The throughput is the sum of speeds times the lowest quality. Find an input where it is wrong.
def best_throughput(speeds, qualities, k):
order = sorted(range(len(speeds)), key=lambda i: -speeds[i])[:k]
return sum(speeds[i] for i in order) * min(qualities[i] for i in order)Totals outgrow 32 bits. A team of 100,000 servers with speed 1,000 and quality 1,000 scores 100,000,000,000, which is far above the 2,147,483,647 an int holds. The campaign targets reach 100,000,000,000,000, so use 64-bit values.
Solve them in this order. The first acts at once on the best allowed option. The second acts late, only when stuck. The third sorts by one key and keeps a heap on another.
Before you code each problem, write three lines: what makes an option allowed, the order the options open in, and what makes one better than another. If the second line is hard to write, the sort key is not clear yet.
Give each problem about 30 minutes. Spend the first five on the three lines, then trace a case with three or four options by hand, showing the heap after each step.
Three cases come back on every rung. The heap is empty when you must act. The target is already met at the start. Two options tie.
Write one small test for each. When a solution fails, look at what the heap holds when it first goes wrong. The heap should hold exactly the allowed options, so an option missing from it or one that should not be in it is the usual cause.
Checkpoint · Greedy with heaps
Q1/5 In the campaigns problem, which affordable campaign do you run each round?
Answer: B
Each round spends one campaign, so choose the one that leaves the most budget. With a budget of 3 and the lesson's list, the cheapest-first rule needs 4 campaigns and the largest gain needs 3.
Q2/5 In the refuel problem, when do you stop at a station?
Answer: C
Every station is free to pass and remembered in the heap. A stop is paid for only when needed, and the largest charge gives the most reach for that one stop.
Q3/5 In the team problem, why are the servers sorted by quality from high to low?
Answer: B
The score multiplies the sum of speeds by the lowest quality. With the sort, the lowest quality is the newest server's, and the heap only has to keep the k fastest speeds.
Q4/5 The speeds are 2, 10, 3, 1, 9, the qualities are 5, 4, 3, 9, 2 and k is 3. Choosing the 3 fastest servers scores 44. What is the best score?
Answer: C
The best group is the servers with speeds 1, 2 and 10, with a sum of 13 and a lowest quality of 4. That scores 52, which the fastest three, with a lowest quality of 2, do not reach.
Q5/5 The refuel scan reaches a point it cannot reach, and the heap of passed stations is empty. What does it return?
Answer: C
With no passed station left to stop at, nothing can add reach, so the destination cannot be reached.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.