progress

~/problems / Binary search / Prefix sums + binary search

How far does the ticket money go?

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A train runs forward through stations 0..n; the leg from i to i + 1 costs fares[i] coins (at least 1). A traveller boards at s with money and pays for each next leg while they can.

Write stations_ridden(fares: list[int], travellers: list[tuple[int, int]]) -> list[int] returning how many legs each (s, money) traveller rides.

fares = [3, 1, 4, 1, 5]            # stations 0..5
stations_ridden(fares, [(0, 8), (2, 4), (1, 100), (4, 4), (5, 9)])   # [3, 1, 4, 0, 0]
# (0, 8):   3 + 1 + 4 = 8 exactly, the next leg costs 1 more  -> 3 legs
# (2, 4):   4 is affordable, 4 + 1 = 5 is not                 -> 1 leg
# (1, 100): rides all 4 remaining legs to station 5            -> 4 legs
# (4, 4):   the only leg left costs 5                           -> 0 legs
# (5, 9):   already at the last station                         -> 0 legs

Up to 10^5 fares and travellers; money <= 10^15. ⭐ Bonus: a speed test earns a star at O(log n) per traveller.

Show hint

with prefix sums P, the farthest station is the last t with P[t] <= P[s] + money: one bisect_right.

Topic: Prefix sums + binary search. Weighted sampling: bisect into cumulative weights.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc