Bank app~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-121kadane
A savings app shows the unit price of an index fund for each day. A saver may buy one unit on one day and sell it on a later day, once.
The app wants to tell savers the best profit that was possible in the past. The profit is the sell price minus the buy price. If the price only fell, the best choice is not to trade, and the profit is 0.
Write best_trade(prices).
prices[i] is the price of one unit on day i, in units of money.i and a sell day j with i < j. The profit is prices[j] - prices[i].Input: prices = [12, 9, 14, 8, 15, 11, 7, 10]
Output: 7The best trade buys at 8 on day 3 and sells at 15 on day 4: a profit of 7.
The profit of a trade is the sum of the day-to-day changes between the two days, so the best trade is the best run of changes.
| Day | Price | Change | Extend | best_here | best_so_far |
|---|---|---|---|---|---|
| 1 | 9 | -3 | -3 | 0 | 0 |
| 2 | 14 | 5 | 5 | 5 | 5 |
| 3 | 8 | -6 | -1 | 0 | 5 |
| 4 | 15 | 7 | 7 | 7 | 7 |
| 5 | 11 | -4 | 3 | 3 | 7 |
| 6 | 7 | -4 | -1 | 0 | 7 |
| 7 | 10 | 3 | 3 | 3 | 7 |
When the extended run is below 0, best_here starts again at 0, which means no trade is open.
Input: prices = [9, 7, 4, 3]
Output: 0The price only falls, so the best choice is not to trade.
Input: prices = [5]
Output: 0One day has no later day to sell on.
1 ≤ prices.length ≤ 100,000 (days of price history)1 ≤ prices[i] ≤ 1,000,000,000 (price of one unit)Trying every buy day and every later sell day examines about n × n / 2 pairs, which is 4,999,950,000 at n = 100,000. A single pass costs about n steps. A profit is below 10^9, so it fits in 32 bits, but the code uses 64-bit integers anyway.