Payments app~15 min2s · 256 MBtarget O(n) time, O(1) spaceprefix-sums
A payments app keeps a ledger for each shop. Every entry is a number of units: money in is positive, and money out is negative.
The audit team likes a ledger that can be cut into two parts with the same total. A cut sits between two entries, so each part has at least one entry. A ledger can have several such cuts, and some ledgers have none.
The audit team runs the check on every ledger each night, and a ledger can hold 100,000 entries.
Write balanced_cuts(ledger).
i splits the ledger into ledger[0..i] and ledger[i + 1..n - 1], for i from 0 to n - 2. Both parts are never empty.Input: ledger = [2, -1, 3, 0, 4]
Output: 2The grand total is 8, so a cut is balanced when the left total is 4.
| Cut after place | Left total | Right total | Balanced |
|---|---|---|---|
| 0 | 2 | 6 | no |
| 1 | 1 | 7 | no |
| 2 | 4 | 4 | yes |
| 3 | 4 | 4 | yes |
Input: ledger = [1, 2]
Output: 0The only cut leaves 1 on the left and 2 on the right.
Input: ledger = [0, 0]
Output: 1One cut, and both parts are 0.
2 ≤ ledger.length ≤ 100,000 (entries in one ledger)-1,000,000 ≤ ledger[i] ≤ 1,000,000 (units, signed)There are up to 99,999 cuts. Adding up both parts for every cut costs about n × n = 10^10 additions. That is too slow.
One pass with a running total tests each cut in O(1). Totals reach 10^11, so use 64-bit integers.