Bank app~40 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-862monotonic-deque
A bank app records the net change of an account for each day, in minor units. A deposit day is positive, a withdrawal day is negative, and a day can be zero.
A savings feature looks for the shortest run of consecutive days whose total change reaches a target. The list can hold 200,000 days. Withdrawals mean that adding more days can make the total smaller, so a window that only grows and shrinks does not work.
Write shortest_run_reaching(changes, target).
changes[i] is the net change of day i. It can be negative or zero.target.Input: changes = [3, -2, 4, -5, 6], target = 5
Output: 1Write the prefix totals: prefix[i] is the total of the first i days, so a run from day a to day b - 1 has total prefix[b] - prefix[a]. Keep a queue of starting positions whose prefix totals rise from the front to the back. At each end, take every front start that reaches the target, and remove it.
End e |
prefix[e] |
Starts that reach the target | Queue of starts after adding e |
Shortest so far |
|---|---|---|---|---|
| 0 | 0 | none | 0 | none |
| 1 | 3 | none | 0, 1 | none |
| 2 | 1 | none (start 1, with prefix 3, is removed from the back) | 0, 2 | none |
| 3 | 5 | start 0: 5 - 0 = 5, length 3 | 2, 3 | 3 |
| 4 | 0 | none (the starts 2 and 3 are removed from the back) | 4 | 3 |
| 5 | 6 | start 4: 6 - 0 = 6, length 1 | 5 | 1 |
The single day with change 6 reaches the target, so the answer is 1.
Input: changes = [2, 2], target = 9
Output: -1The total of all days is 4, so no run reaches 9.
Input: changes = [-4, 8, -1], target = 8
Output: 1The second day alone reaches the target.
1 ≤ length of changes ≤ 2 × 10^5, and -10^5 ≤ changes[i] ≤ 10^51 ≤ target ≤ 10^9Trying every start and adding days until the total reaches the target costs up to n × n / 2 steps. For n = 200,000 and an unreachable target, that is about 2 × 10^10 steps.
A prefix total can reach 2 × 10^10 in size, which is more than a 32-bit int holds, so prefix totals are 64-bit. Each position joins the queue once and leaves it at most once, so the pass costs O(n).