Four problems that walk a line once. The move: keep one frontier number, compare it with the next demand, and push it as far as it goes. A failure rules out whole stretches of starts.
You work on a messaging service, a cash-collection app, a reading app and a job queue. The four problems on this street all walk a line once. At each step they keep one number, and the number never goes back.
What the number is changes from problem to problem. Here is each one.
| Problem | The number that moves | It is compared with | Each step |
|---|---|---|---|
| Reach the last relay with one signal booster | the farthest relay reached | the next relay's position | extend it by the relay's reach |
| First branch for a cash van with a capped vault | the cash in hand, at most the cap | the next payout | add the deposit, cap it, pay |
| Farthest card after a number of skips | the farthest card of this layer | the cards not yet scanned | scan them and start the next layer |
| Longest cooldown that leaves no idle time | the rows the commonest job fills | the number of jobs | solve for the cooldown with a formula |
In the first three, the comparison tells you whether you can go on. In the fourth, the number is a count, and the schedule is never built.
Exercise · Predict the output: How many skips reach the end?. The code counts the skips that a reader needs to reach the last card. A skip moves forward by up to the reach of the card it leaves. What does it print?
reach = [1, 3, 1, 0, 4, 1, 0, 0]
skips = 0
end = 0
far = 0
for i in range(len(reach) - 1):
far = max(far, i + reach[i])
if i == end:
skips += 1
end = far
print(skips)Name the frontier before you code. It is the best value that any plan can have after the items you have scanned.
At each step, compare it with the next demand. If the demand is beyond the frontier, no earlier choice can meet it, so the answer is no. Otherwise push the frontier as far as this step allows, and move on.
The frontier is the best value any plan can reach after the steps scanned so far. A demand beyond it cannot be met, and otherwise the frontier moves forward, so nothing is scanned twice.
The cash van problem adds a skip. If the trip from branch s fails at step k, every start from s plus 1 up to s plus k fails too. Each of those starts reaches the failing branch with no more cash than the trip from s had. So the next start to try is s plus k plus 1.
Take deposits 4, 2, 6, 1, 3, 5, payouts 3, 5, 2, 4, 2, 3 and a cap of 6. The first branch that works is branch 2.
A trip from branch 0 fails at branch 1, so skip start 1 and try branch 2, which completes the ring with a cap of 6.
Exercise · Find the bug: The vault that never fills. This finds the first branch from which the van completes the ring, or -1. The vault holds at most cap units. It is wrong on some inputs. Which line is wrong?
def first_start_with_cap(deposits, payouts, cap):
n = len(deposits)
start = 0
while start < n:
cash = 0
failed_at = -1
for step in range(n):
i = (start + step) % n
cash = cash + deposits[i]
if cash < payouts[i]:
failed_at = step
break
cash -= payouts[i]
if failed_at < 0:
return start
start += failed_at + 1
return -1The Academy lesson Greedy choices keeps the farthest position reached on one list. Running balances and two passes restarts a scan after a failure. This street does not teach those again. It changes four things.
A booster means a second scan. The first scan finds the farthest relay without help. The booster lifts it by the boost, and the relays beyond may reach farther, so scan again from the start.
With reach 2, 2, 0, 0, 3, 1 the farthest relay is 3. Adding 1 gives 4, which is short of the last relay, but relay 4 reaches 7, so the answer is yes. Without the booster it is no.
A cap breaks the totals. Without a cap you can decide from the sum of deposits and payouts. With a cap, cash above the limit is lost, so the order matters.
On the cash van example the answer is branch 2 with a cap of 6, and -1 with a cap of 5. Run the trip, and skip the starts that the failure rules out.
Many budgets mean keeping the layers. The farthest card after each skip is a layer, and one pass builds them all.
For reach 2, 3, 1, 0, 4, 1, 0, 0 the layers end at cards 0, 2, 4 and 7. The budgets 0, 1, 2, 3 and 10 then give 0, 2, 4, 7 and 7.
Sometimes the schedule is never built. The commonest job occurs m times, and k jobs share that count. The jobs fill m minus 1 rows of cooldown plus 1 slots, then a last row of k. For AABBBC that gives 2 rows of 2 and a last row of 1, so a cooldown of 1 fits and 2 does not.
For jobs AABB the last row holds two jobs, not one: assuming one gives a cooldown of 2 where the true answer is 1.
Exercise · Put it in order: Scan, boost, scan again. Arrange the lines into a function that says whether the message reaches the last relay when the booster is used once. One line is a distractor.
def can_reach_with_boost(reach, boost):
n = len(reach)
far = 0
for turn in range(2):
i = 0
while i <= far and i < n:
far = max(far, i + reach[i])
i += 1
if turn == 0:
far += boost
return far >= n - 1
far += boost + 1Exercise · Break it: Jobs that share the top count. This returns the longest cooldown that leaves no idle time. It counts the commonest job but ignores how many kinds share the top count. Find an input where it is wrong.
def longest_cooldown(jobs):
counts = {}
for kind in jobs:
counts[kind] = counts.get(kind, 0) + 1
n = len(jobs)
m = max(counts.values())
if m == 1:
return n
return (n - 1) // (m - 1) - 1Solve them in this order. The first adds a booster to a plain reach scan. The second adds a cap and the skip rule. The third answers many budgets, and the fourth counts rows instead of building a schedule.
Before you code each problem, write two lines: the number that moves forward, and what it is compared with. If the second line is a count of items, look for a closed formula.
Give each problem about 25 minutes. Spend the first five on the two lines and a hand trace of a short input, then code it.
Three cases come back on almost every rung. The list has one item. The frontier cannot move at all. Two jobs tie for the top count.
Write one small test for each. When a solution fails, run your trace on the failing input and compare the frontier at each step. The first step where it differs from your hand trace is the bug.
Checkpoint · Scheduling greedy
Q1/5 In a reach scan, the next position is beyond the frontier. What does that tell you?
Answer: B
The frontier is the best any plan can reach so far. A demand beyond it cannot be met by any plan.
Q2/5 The relays reach 2, 2, 0, 0, 3, 1 and the booster adds 1 once. The farthest relay without help is 3. Why is the answer still yes?
Answer: C
After the boost the frontier is 4, which is short of the last relay at 5. Relay 4 reaches 7, so scanning again from the start gets there.
Q3/5 A trip from branch 3 fails at step 2. What is the next start to try?
Answer: B
The failure rules out the starts from 4 up to 3 plus 2, which is 5. The next start to try is 3 plus 2 plus 1, which is 6.
Q4/5 Why can the totals of deposits and payouts not decide the cash van problem once the vault has a cap?
Answer: B
With deposits 4, 2, 6, 1, 3 and 5 and payouts 3, 5, 2, 4, 2 and 3, a cap of 6 gives branch 2, and a cap of 5 gives -1.
Q5/5 The jobs are AABB. The commonest job occurs twice, and two kinds share that count. What is the longest cooldown with no idle time?
Answer: B
The last row holds two jobs, so the rows use 1 times the cooldown plus 1, plus 2, which must fit in 4. A cooldown of 1 fits and 2 does not.
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.