Bank app~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-327divide-and-conquer · prefix-sums · sorting
A bank keeps a ledger of signed entries in minor units, with credits negative. An audit counts the runs of consecutive entries whose total lies inside a band from low to high, both ends included. A run holds at least one entry. The ledger can hold 100,000 entries, so checking every run one by one is too slow.
Write count_range_sums(amounts, low, high).
amounts is the ledger, in order.amounts[i..j] with i <= j.s with low <= s <= high.Input: amounts = [2, -3, 4, 1], low = 1, high = 4
Output: 7Build the prefix sums, so a run total is a difference of two prefix sums. Then count the pairs with merge sort: at each merge, two pointers count the matches across the halves.
The prefix sums are [0, 2, -1, 3, 4].
| Halves merged (each already sorted) | Pairs counted across them |
|---|---|
| [0] and [2] | 1 |
| [3] and [4] | 1 |
| [-1] and [3, 4] | 1 |
| [0, 2] and [-1, 3, 4] | 4 |
The total of pairs counted is 7.
Input: amounts = [5], low = 5, high = 5
Output: 1The only run is [5], and its total 5 is in the band: 1.
Input: amounts = [1, 1, 1], low = 10, high = 20
Output: 0No run reaches 10, so the count is 0.
0 ≤ amounts.length ≤ 100,000 (entries)-1,000,000 ≤ amounts[i] ≤ 1,000,000 (minor units)-10^11 ≤ low ≤ high ≤ 10^11Checking every run costs about n × n / 2, which is 5 × 10^9 at n = 100,000. Merge sort costs n log n, and the counting pass inside each merge costs the size of the merge.