Courier Pay with Overlap Multipliers, Waits and Peak Windows
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Sweep-line over time intervals: pay grows with the square of concurrent deliveries, store-wait minutes are isolated, and peak windows double the rate.
Courier Pay Calculator
A delivery platform pays couriers per minute of work. Time is measured in whole minutes, and every time range is half-open: a range [s, e) covers minutes s, s+1, ..., e-1 and does not include minute e. A range with s >= e is empty and contributes nothing.
Input
orders: a list of dictionaries. Each has:"accepted_at"and"delivered_at"(integers), always present."arrived_at"and"picked_up_at"(integers), optional.
rate: an integer, the base pay per minute.peak_intervals: a list of[start, end]pairs describing peak windows, each read as the half-open range[start, end).
Pay rules
Shared minutes. For every minute, let k be the number of orders that are shared-active in that minute. Each shared-active order earns rate * k for that minute, so the minute pays k * k * rate in total.
Which minutes are shared-active.
- If an order lacks
"arrived_at"or lacks"picked_up_at"(or both), it has no store wait. It is shared-active on[accepted_at, delivered_at). - If an order has both
"arrived_at"and"picked_up_at", it is split into three pieces:[accepted_at, arrived_at)is shared-active.[picked_up_at, delivered_at)is shared-active.[arrived_at, picked_up_at)is the store-wait piece. It is not shared-active, so it does not count towardkfor any order (including itself). Each of its minutes pays exactlyrate, independent of every other order.
- Use the three pieces exactly as the given numbers define them. Any piece with start
>=end is empty and ignored. Do not clip pieces to the order's other timestamps.
Peak windows. A minute is a peak minute if it lies in at least one of the peak intervals. Overlapping or touching peak intervals form a union, and a minute covered by several of them is still just one peak minute. Everything paid for a peak minute is doubled, both shared pay (2 * k * k * rate) and store-wait pay (2 * rate). Peak intervals with start >= end are ignored.
Task
Return the total pay (an integer) summed over all minutes and all orders.
If orders is empty, the answer is 0.
Constraints
- Timestamps are integers and can be large, so iterating minute by minute is not a good idea.
rateis a non-negative integer.- The number of orders and the number of peak intervals are each modest enough for an
O((N + P) log (N + P))solution, plus a pass over the orders for the waits. - Back-to-back ranges (one ends at minute
t, another starts att) do not overlap. - Several orders may share identical timestamps.
Examples
Example 1
Input: compute_courier_pay([{'accepted_at': 0, 'delivered_at': 3}, {'accepted_at': 1, 'delivered_at': 4}], 2, [])
Output: 20
Example 2
Input: compute_courier_pay([{'accepted_at': 0, 'arrived_at': 1, 'picked_up_at': 3, 'delivered_at': 4}, {'accepted_at': 1, 'delivered_at': 3}], 1, [[2, 4]])
Output: 9
Hints
Hint 1
The total only depends on how many shared-active orders there are at each minute, not on which ones. Between two consecutive 'interesting' timestamps that count is constant.
Hint 2
Turn every shared-active piece into a +1 event at its start and a -1 event at its end, and add +1/-1 events for the merged peak windows too. Sort the distinct timestamps and charge each gap as length * rate * k * k * (2 if inside a peak else 1), applying the deltas after charging.
Hint 3
Keep store-wait pieces out of the sweep entirely and pay them separately at multiplier 1. For each one, add rate times (its length plus the number of its minutes that fall inside the merged peak union).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The pay for a minute is k * k * rate (times 2 on a peak minute), where k is the number of shared-active orders in that minute. It depends only on k and on whether the minute is a peak minute, so a sweep line over timestamps works.
- Merge the peak windows into a union of disjoint intervals, so a minute covered by several windows is doubled only once.
- Build events. Each shared-active piece
[s, e)withs < eadds+1to the active count atsand-1ate. Orders with both optional timestamps are split into[accepted, arrived)and[picked_up, delivered), and the store-wait piece stays out of the sweep. Each merged peak window adds+1to a peak counter at its start and-1at its end. Events at equal timestamps share one dictionary entry. - Sweep the sorted distinct timestamps. Between the previous timestamp and the current one, the active count and peak status are constant, so that gap pays
gap * rate * active^2 * (2 if peak else 1). Charge the gap first, then apply the deltas at the current timestamp. This respects the half-open rule: a piece ending attis already gone at minutet, and one starting attis already present. - Store waits. Each wait
[arrived, picked_up)paysrateper minute with multiplier 1. Its peak minutes (the overlap with the merged windows) are paid a second time, so it addsrate * (length + peak_overlap).
Why it is correct
- Nothing changes between consecutive event times, so the closed-form charge per gap is exact.
- Charging before applying deltas implements the half-open semantics, so back-to-back pieces never overlap.
- Waits neither raise anyone's
knor have their ownkraised, so they are exactly an independentk = 1timeline, and pay is additive across minutes. - Merging peak windows guarantees the factor is exactly 1 or 2.
- Empty pieces are skipped, so degenerate ranges add nothing.
Complexity
With N orders and P peak intervals:
- Sorting events:
O((N + P) log (N + P)), since there are at most4N + 2Pevents. - Sweep:
O(N + P). - Wait overlaps: the reference scans the merged windows per wait, so
O(N * P)worst case. Binary search plus prefix sums of window lengths makes each queryO(log P). - Space:
O(N + P).
Reference solution
from typing import Dict, List
def compute_courier_pay(orders: List[Dict], rate: int, peak_intervals: List[List[int]]) -> int:
# Union of peak windows so overlaps never double the rate twice.
windows = sorted((s, e) for s, e in peak_intervals if s < e)
merged = []
for s, e in windows:
if merged and s <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], e)
else:
merged.append([s, e])
# events[t] = [change in shared-active count, change in peak depth]
events = {}
for order in orders:
accepted = order['accepted_at']
delivered = order['delivered_at']
if 'arrived_at' in order and 'picked_up_at' in order:
pieces = [(accepted, order['arrived_at']),
(order['picked_up_at'], delivered)]
else:
pieces = [(accepted, delivered)]
for s, e in pieces:
if s < e:
events.setdefault(s, [0, 0])[0] += 1
events.setdefault(e, [0, 0])[0] -= 1
for s, e in merged:
events.setdefault(s, [0, 0])[1] += 1
events.setdefault(e, [0, 0])[1] -= 1
total = 0
active = 0
peak_depth = 0
prev = None
for t in sorted(events):
if prev is not None and t > prev:
factor = 2 if peak_depth > 0 else 1
total += (t - prev) * rate * active * active * factor
d_active, d_peak = events[t]
active += d_active
peak_depth += d_peak
prev = t
# Store-wait minutes: paid alone, doubled only on peak minutes.
for order in orders:
if 'arrived_at' not in order or 'picked_up_at' not in order:
continue
s = order['arrived_at']
e = order['picked_up_at']
if s >= e:
continue
peak_minutes = 0
for ps, pe in merged:
if pe <= s:
continue
if ps >= e:
break
peak_minutes += max(0, min(e, pe) - max(s, ps))
total += rate * ((e - s) + peak_minutes)
return total