Ride-hailing app~25 min2s · 256 MBtarget O(n + q log n) time, O(n) spaceclassic twin: lc-209prefix-sums
A ride-hailing app records the number of trips requested in each minute of a day. No minute has a negative count. Dispatchers ask the same question many times: starting at a given minute, how soon do the requests add up to a target?
Each question gives a start minute and a target. The answer is the length of the shortest run of minutes that begins at the start minute and has a total of at least the target.
A day has up to 100,000 minutes, and there can be 100,000 questions. A question is answered alone, so the run must start exactly at the start minute.
Write shortest_run_from(loads, queries).
loads[i] is the number of trip requests in minute i. It is never negative.queries[j] is [start, target], with 0 ≤ start < loads.length and target ≥ 1.k such that loads[start] + ... + loads[start + k - 1] ≥ target, or 0 when no such run exists.Input: loads = [2, 3, 1, 2, 4, 3], queries = [[0, 7], [2, 6], [1, 20], [3, 5]]
Output: [4, 3, 0, 2]The table of prefix totals is [0, 2, 5, 6, 8, 12, 15]. A run from start reaches target at the first end whose prefix total is at least prefix[start] + target.
| Start | Target | Goal | First end | Answer |
|---|---|---|---|---|
| 0 | 7 | 7 | 4 | 4 |
| 2 | 6 | 11 | 5 | 3 |
| 1 | 20 | 22 | none | 0 |
| 3 | 5 | 11 | 5 | 2 |
Input: loads = [5], queries = [[0, 5]]
Output: [1]One minute is enough when its count equals the target.
Input: loads = [0, 0, 0], queries = [[1, 1]]
Output: [0]Every count is 0, so no run reaches 1.
1 ≤ loads.length ≤ 100,000 (minutes)0 ≤ loads[i] ≤ 1,000,000 (trip requests in one minute)0 ≤ queries.length ≤ 100,000, and each query is [start, target] with 0 ≤ start < loads.length and 1 ≤ target ≤ 1,000,000,000Adding up minutes from the start of each query costs up to n steps per query. For 100,000 queries on 100,000 minutes that is up to 10,000,000,000 additions.
A sliding window answers one target in one pass, but here the start changes for each query. A table of prefix totals is built once, and then each query is one binary search. The totals reach 10^11, so use 64-bit integers.