Five problems where a greedy rule needs a reason. The move: swap any best plan toward the rule and show it is never worse. When no swap fits, two lower bounds do the same job.
You work on a charging network, a voucher system, a server fleet and a rewards app. The five problems on this street come from all four. Each has a greedy rule that looks right in a minute and breaks on a small input.
The rule itself is short. The work is knowing why it holds. Here is each rule, and the reason behind it.
| Problem | The greedy rule | Why it holds |
|---|---|---|
| Match scooters to docks within a power band | match the weakest scooter with the weakest dock that fits | swap the pair into any better plan |
| Orders that print the largest voucher code | a goes before b when ab is larger than ba | swap two neighbours |
| Smallest memory limit for a fixed fleet | pair the lightest with the heaviest of the lightest block | swap the partners |
| Spend tokens for the best score | redeem the cheapest, cash in the dearest | swap the roles of two tokens |
| Candy distribution | take the larger of the left and right demands | two lower bounds, no swap |
A wrong rule is easy to find. For the scooters, give each one, from the weakest, the strongest dock in its band. With needs 1, 2, docks 1, 2 and a slack of 1, that charges one scooter, and matching the weakest fit charges two.
Take a best plan that does not agree with the rule at one place. Swap two items so that it does. If the swapped plan is still valid and no worse, then some best plan agrees with the rule there. Repeat for the next choice, and the whole rule is justified.
Some best plan agrees with every choice the rule has made so far. A swap that keeps a plan valid and no worse is what keeps this true at the next choice.
The tokens problem shows it. The rule is to redeem the cheapest token. Suppose a best plan redeems a dearer token y while a cheaper token x is unused. Redeem x instead: the credits afterwards are higher by y minus x, so every later move is still allowed.
The same swap works at the other end, and a score that can be given back needs both ends. With tokens 90, 150, 40, 260, 70 and 100 credits, redeeming without ever cashing in reaches a score of 1. The two-ended rule reaches 3.
Redeem the cheapest token you can afford, and cash in the dearest when you cannot: a score of 3 where redeeming alone reaches 1.
Exercise · Predict the output: How high does the score go?. The tokens are sorted. The code redeems the cheapest token when it can afford it, and otherwise cashes in the dearest one for credits. What does it print?
tokens = [40, 70, 90, 150, 260]
credits = 100
low = 0
high = len(tokens) - 1
score = 0
best = 0
while low <= high:
if credits >= tokens[low]:
credits -= tokens[low]
low += 1
score += 1
best = max(best, score)
elif score > 0:
credits += tokens[high]
high -= 1
score -= 1
else:
break
print(best)The Academy lesson Sort, then choose finds a sort key by swapping two neighbours, and Greedy choices shows when a local choice is safe. Running balances and two passes scans a list in both directions. This street does not teach those again. It adds four things.
Ties change the count. The voucher problem asks how many orders print the largest code. Fragments tie when both joins are equal, and that is not the same as equal numbers: 3, 33 and 333 tie, so the best code has 6 orders. Multiply the factorial of each tied run, so 1, 1, 2, 2, 2 gives 2 times 6, which is 12.
A limit fixes the pairs. With a fixed fleet, jobs minus servers servers must hold a pair, and the rest run alone. Only the lightest block of jobs is paired, the lightest with the heaviest of that block.
For loads 3, 5, 3, 4 on 2 servers, that gives pairs 3 plus 5 and 3 plus 4, a limit of 8. Pairing neighbours would give 9.
Exercise · Find the bug: The heaviest job is not a partner. This finds the smallest memory limit when each server holds at most two jobs. It is wrong on some inputs. Which line is wrong?
def smallest_memory_limit(loads, servers):
n = len(loads)
if n > 2 * servers:
return -1
jobs = sorted(loads)
pairs = max(0, n - servers)
limit = 0
for i in range(pairs):
limit = max(limit, jobs[i] + jobs[n - 1 - i])
for i in range(2 * pairs, n):
limit = max(limit, jobs[i])
return limitA score that can be given back needs two ends. The tokens problem has the cheap end and the dear end of one sorted list, as the prediction showed.
Sometimes no swap fits. In the bonus units problem, a rule between two neighbours links every account to a run of others. Each pass gives a lower bound from one side, and the larger bound at each account is the least valid plan.
On ratings 1, 3, 2, 2, 1, the left pass alone totals 6 and the full plan totals 7. On 3, 2, 1 the left pass alone totals 3 and the plan totals 6. A strictly rising list of 100,000 accounts totals 5,000,050,000 units, so the sum needs 64 bits.
One pass gives one lower bound: on ratings 3, 2, 1 the left pass totals 3, while both passes total 6.
Exercise · Put it in order: Two passes, keep the larger demand. Arrange the lines into a function that returns the fewest bonus units. The right pass must keep the larger demand. One line is a distractor.
def fewest_bonus_units(ratings):
n = len(ratings)
bonus = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
bonus[i] = bonus[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
bonus[i] = max(bonus[i], bonus[i + 1] + 1)
return sum(bonus)
bonus[i] = bonus[i + 1] + 1Exercise · Break it: Reverse alphabetical order. This builds the largest code from fragments by sorting their text in reverse alphabetical order. Find an input where the code is not the largest.
def largest_code(pieces):
texts = sorted((str(p) for p in pieces), reverse=True)
return "".join(texts)Solve them in this order. The first is the plainest swap. The next three add a pair rule with ties, a fixed number of pairs and two ends. The last has no swap at all.
Before you code each problem, write two lines: the rule, and the swap that shows it is safe. If you cannot write the second line, look for a lower bound from each side, as in the last problem.
Give each problem about 25 minutes. Write the rule and the swap first, then break the rule on a case with three or four items before you code it.
Three cases come back on almost every rung. Two items tie, a limit makes some items run alone, and a total grows past 32 bits. Write one small test for each.
When a solution fails, try the next-best rule by hand on the failing input. If a swap shows the rule is still safe, the bug is in the code. If it does not, the rule is wrong.
Checkpoint · Exchange arguments
Q1/5 What does an exchange argument show about a greedy rule?
Answer: B
If a swap keeps a best plan valid and no worse, some best plan agrees with the rule at that choice, and repeating it justifies the whole rule.
Q2/5 Voucher fragments 3, 33 and 333 are joined in every order. How many orders print the largest code?
Answer: C
All six joins print the same digits, so the fragments tie. The count is the factorial of the size of the tied run, which is 3 factorial.
Q3/5 Three jobs run on two servers, and each server holds at most two jobs. Which jobs are paired?
Answer: C
Jobs minus servers servers must hold a pair, here one. Pairing the heaviest job with a light one wastes a server and raises the limit.
Q4/5 In the tokens problem, why does the rule need to cash in the dearest token as well as redeem the cheapest?
Answer: B
With tokens 40, 70, 90, 150 and 260 and 100 credits, redeeming alone stops at a score of 1. Cashing in 260 once reaches 3.
Q5/5 In the bonus units problem, why is the left pass alone not enough?
Answer: C
On ratings 3, 2 and 1 the left pass gives a total of 3, but the right neighbour rule needs 6. The right pass adds the second lower bound.
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.