Bank app~12 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
A bank app shows the ledger of one account for a day. Each entry is a whole number in minor units: a positive entry is a credit, and a negative entry is a debit. The account starts the day with a balance of 0.
The risk team wants the lowest balance the account reached at any moment of the day, including the start. You trace a small ledger by hand to get the rule right, and you check the size of the largest balances before you submit.
Write lowest_balance(entries).
entries[i] is the amount of entry i, in order. The balance starts at 0 and changes by each entry in turn.i is the sum of entries 0 to i.Input: entries = [50, -80, 30, -40, 100]
Output: -40| Entry | Amount | Balance after it | Lowest so far |
|---|---|---|---|
| start | 0 | 0 | |
| 0 | 50 | 50 | 0 |
| 1 | -80 | -30 | -30 |
| 2 | 30 | 0 | -30 |
| 3 | -40 | -40 | -40 |
| 4 | 100 | 60 | -40 |
Input: entries = [10, 20]
Output: 0The balance only rises, so the lowest moment is the start, 0.
Input: entries = [-5]
Output: -5One debit takes the balance from 0 to -5.
0 ≤ entries.length ≤ 100,000 (entries in one day)-1,000,000,000 ≤ entries[i] ≤ 1,000,000,000 (amounts in minor units)Adding the first i entries again for every i costs about n × n / 2 = 5 × 10^9 additions at n = 100,000. That is too slow. Keep one running balance. The balance can reach 10^14, so it needs a 64-bit integer.