Payments app~18 min2s · 256 MBtarget O(n) time, O(1) spacekadane
A payments app keeps the closing balance of a merchant wallet for each day, in units. The risk team looks at the worst drawdown. That is the biggest fall from the balance on one day, the peak, to a lower balance on a later day, the trough.
For each wallet the team wants the peak day, the trough day and the size of the fall. A wallet whose balance never falls has no drawdown.
Write worst_drawdown(balances).
balances[i] is the closing balance on day i, in units.balances[p] - balances[t] for days p ≤ t. Find the largest fall.[p, t, fall]: the peak day, the trough day and the size of the fall.[0, 0, 0].Input: balances = [50, 80, 65, 90, 40, 70, 30, 60]
Output: [3, 6, 60]The balance peaks at 90 on day 3 and falls to 30 on day 6: a fall of 60.
Keep the peak day so far, and measure the fall from it on each day.
| Day | Balance | Peak day | Fall | Best fall |
|---|---|---|---|---|
| 1 | 80 | 1 | 0 | 0 |
| 2 | 65 | 1 | 15 | 15 |
| 3 | 90 | 3 | 0 | 15 |
| 4 | 40 | 3 | 50 | 50 |
| 5 | 70 | 3 | 20 | 50 |
| 6 | 30 | 3 | 60 | 60 |
| 7 | 60 | 3 | 30 | 60 |
A new high on day 3 moves the peak, so the fall to 30 is measured from 90 and not from 80.
Input: balances = [10, 20, 30]
Output: [0, 0, 0]The balance only rises, so there is no fall.
Input: balances = [7]
Output: [0, 0, 0]One day has no later day.
1 ≤ balances.length ≤ 100,000 (days of history)0 ≤ balances[i] ≤ 1,000,000,000 (closing balance in units)Trying every peak day and every later trough day costs about n × n / 2 pairs, which is 5,000,050,000 at n = 100,000. A single pass costs about n steps. A fall is at most 10^9, and the code uses 64-bit integers for it anyway.