Online store~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-53kadane
An online store shows its net revenue change for each day, in units. Sales add to the number and refunds take from it, so some days are negative.
Marketing wants to know which stretch of consecutive days earned the most in total. A stretch is one or more days in a row. The dashboard keeps up to 100,000 days and refreshes every few seconds.
Write best_revenue_run(revenue).
revenue[i] is the net revenue change on day i, in units. It can be negative or zero.Input: revenue = [3, -8, 5, 2, -4, 6, -9, 2]
Output: 9The best run is days 2 to 5: 5 + 2 + (-4) + 6 = 9.
| Day | Change | Extend | best_here | best_so_far |
|---|---|---|---|---|
| 0 | 3 | 3 | 3 | |
| 1 | -8 | 3 + (-8) = -5 | -5 | 3 |
| 2 | 5 | -5 + 5 = 0 | 5 | 5 |
| 3 | 2 | 5 + 2 = 7 | 7 | 7 |
| 4 | -4 | 7 + (-4) = 3 | 3 | 7 |
| 5 | 6 | 3 + 6 = 9 | 9 | 9 |
| 6 | -9 | 9 + (-9) = 0 | 0 | 9 |
| 7 | 2 | 0 + 2 = 2 | 2 | 9 |
At day 2 the old run is worth -5, so the run starts again at 5. The answer is the largest best_so_far, 9, not the last best_here, 2.
Input: revenue = [-7, -3, -8]
Output: -3Every day is a loss. The best run is the single day with -3.
Input: revenue = [12]
Output: 12One day is one run.
1 ≤ revenue.length ≤ 100,000 (days on the dashboard)-1,000,000 ≤ revenue[i] ≤ 1,000,000 (net change in units)Trying every start day and every end day examines about n × n / 2 runs, which is 5,000,050,000 at n = 100,000. At a nanosecond each, that is about 5 seconds. A single pass costs about n steps. The totals can reach 10^11, so use 64-bit integers.