progress

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

How many items fit the budget

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 Uber

Stalls 1..n line a street, stall i selling one item for prices[i - 1], with prices never decreasing. A shopper enters at a stall, walks to the end, and buys at most one item per stall within budget.

Implement max_items(prices: list[int], pos: list[int], amount: list[int]) -> list[int]: for each query j (enter at stall pos[j], 1-indexed, with budget amount[j]), the most items they can buy.

prices = [2, 3, 3, 7, 10]
max_items(prices, [1, 2, 4, 5, 3], [8, 5, 100, 9, 0])
# [3, 1, 2, 0, 0]
# stall 1, budget 8:   2 + 3 + 3 = 8
# stall 2, budget 5:   3 (3 + 3 = 6 is over)
# stall 4, budget 100: 7 + 10
# stall 5, budget 9:   the only item costs 10

Up to 100,000 stalls and queries; budgets up to 10**15. ⭐ Bonus: a speed test earns a star at O(log n) per query.

Show hint

the best buy is always the next few stalls in a row. Build prefix sums pre, with pre[0] = 0 and pre[i] = prices[0] + ... + prices[i - 1], then binary search them for budget + pre[p - 1].

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

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