Bank app~15 min2s · 256 MBtarget O(n) time, O(1) spaceprefix-sums
A bank app lets a business plan tomorrow's account activity. The finance team enters the day's expected entries in order: deposits are positive and payments out are negative.
The account must never go below zero during the day, not even for a moment. The team asks for the smallest amount to put in the account before the first entry.
Write smallest_opening_balance(entries).
entries[i] is the i-th entry of the day in units: positive for money in, negative for money out.b, and apply the entries in order. After every entry the balance must be 0 or more.b that is 0 or more and keeps every balance at 0 or more.Input: entries = [300, -500, 200, -400, 600]
Output: 400The trace starts from an opening balance of 0 and tracks the running total and its lowest point.
| Entry | Running total | Lowest so far |
|---|---|---|
| 300 | 300 | 0 |
| -500 | -200 | -200 |
| 200 | 0 | -200 |
| -400 | -400 | -400 |
| 600 | 200 | -400 |
The running total falls to -400 at its lowest, so 400 units must be in the account at the start. The output is 400.
Input: entries = [100, 250, -50]
Output: 0The running total is 100, 350 and 300. It never goes below zero, so no money is needed at the start.
Input: entries = [-1000000000, -1000000000, -1000000000]
Output: 3000000000Three large payments out need 3,000,000,000 units, which is more than a 32-bit int holds.
1 ≤ entries.length ≤ 100,000 (entries in a day)-1,000,000,000 ≤ entries[i] ≤ 1,000,000,000 (units)Adding up the entries from the start again for every position costs about n × n / 2 additions, about 5 × 10^9 at n = 100,000. One running total does it in n additions. The total can reach 10^5 × 10^9 = 10^14, so it needs a 64-bit integer.