Bank app~20 min2s · 256 MBtarget O(n + q log n) time, O(n) spacebinary-search · prefix-sums
A bank app records how much a customer spends each day. The customer can set a spending limit, and the app tells them on which day the total spent so far first reached the limit.
You get the daily spend for a card, from day 0 on, and a list of limits to check. Each limit is a separate question about the same history.
Write first_days(spend, limits).
spend[i] is the amount spent on day i. It can be zero.i is spend[0] + ... + spend[i].Input: spend = [4, 0, 6, 0, 3], limits = [4, 5, 10, 14]
Output: [0, 2, 2, -1]The running totals are [4, 4, 10, 10, 13]. They never go down, so you can search them. Take the limit 10. The window [lo, hi) holds the days that might be the answer.
| Step | lo | hi | mid | totals[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 10 | 10 is not below 10, so hi = 2 |
| 2 | 0 | 2 | 1 | 4 | 4 < 10, so lo = 2 |
| end | 2 | 2 | day 2 is the first day with a total of at least 10 |
The limit 4 is reached on day 0, and not on day 1 where the total is also 4. The limit 5 is reached on day 2. The limit 14 is above the last total, 13, so its answer is -1.
Input: spend = [], limits = [0, 3]
Output: [-1, -1]With no days there is nothing to reach, so even the limit 0 gets -1.
Input: spend = [2, 2, 2], limits = [0, 2, 6, 7]
Output: [0, 0, 2, -1]The totals are [2, 4, 6]. The limit 0 is reached on day 0, the limit 2 on day 0, and the limit 6 exactly on the last day. The limit 7 is never reached.
0 ≤ spend.length ≤ 100,0000 ≤ spend[i] ≤ 1,000,000, so a day can have zero spend0 ≤ limits.length ≤ 100,0000 ≤ limits[j] ≤ 1,000,000,000,000Adding up days from the start for every limit costs about n × q steps, which is 10^10 when both are 100,000. The running totals never go down, so they are sorted, and a binary search needs about 17 steps per limit. The total can reach 10^11, which does not fit in 32 bits.