Payments app~25 min2s · 256 MBtarget O(n) time, O(1) spacesliding-window-variable
A payments desk watches money moving through a settlement account. Each entry is a signed amount: money in is positive and money out is negative. Entries arrive in time order.
The risk team calls the net of the entries from the last few seconds the net exposure. It matters in both directions: a large net in or a large net out each needs a review. The team wants the largest exposure of the day.
Write largest_net_exposure(times, amounts, span).
i arrives at second times[i] and moves amounts[i] units. The times never go down.i arrives, the window holds every entry j <= i with times[i] - times[j] < span. The entry itself is always in its window.i is the absolute value of the sum of the amounts in its window.long.Input: times = [0, 10, 20, 70, 75, 130], amounts = [500, -200, -900, 400, -100, -300], span = 60
Output: 600The trace keeps the entries inside the window and their net.
| i | Time | Window | Net | Largest so far |
|---|---|---|---|---|
| 0 | 0 | 0 to 0 | 500 | 500 |
| 1 | 10 | 0 to 1 | 300 | 500 |
| 2 | 20 | 0 to 2 | -600 | 600 |
| 3 | 70 | 2 to 3 | -500 | 600 |
| 4 | 75 | 2 to 4 | -600 | 600 |
| 5 | 130 | 4 to 5 | -400 | 600 |
At i = 2 the window holds the three earliest entries, and their net is -600. At i = 3 the entries from times 0 and 10 are 60 seconds old or older, so they leave. The largest exposure is 600.
Input: times = [5, 5, 5], amounts = [400, -400, 250], span = 1
Output: 400With span = 1, only entries in the same second share a window. All three arrive at second 5, so the nets are 400, 0 and 250. The largest exposure is 400.
Input: times = [0, 30, 60, 90], amounts = [-100, -100, -100, -100], span = 61
Output: 300The window of the last entry holds the entries at 30, 60 and 90, because the entry at 0 is 90 seconds old. The net is -300, and its size is 300.
1 ≤ times.length ≤ 100,000 (entries in a day or a month); amounts has the same length0 ≤ times[i] ≤ 2,678,400 (seconds since the start of the month), never going down-1,000,000,000 ≤ amounts[i] ≤ 1,000,000,000 (units; positive is money in)1 ≤ span ≤ 86,400 (seconds)Summing the window again for every entry costs up to n × n / 2 additions, about 5 × 10^9 at n = 100,000. Each entry joins the window once and leaves it once, so a running sum needs only about 2 × n steps. The net can reach 10^5 × 10^9 = 10^14, which needs 64-bit integers.