Bank app~18 min2s · 256 MBtarget O(n) time, O(1) spacegreedy
A savings app lets you buy units of a fund and sell them later. To discourage quick trades, the app allows a sale only when the units have been held for at least hold days.
You know the price of one unit on each day of the past. You want to know the largest profit that one purchase and one later sale could have made under the rule.
Write best_trade_with_hold(prices, hold).
prices[d] is the price of one unit on day d.buy and sells on day sell, where sell - buy >= hold. The profit is prices[sell] - prices[buy].Input: prices = [4, 1, 9, 3, 2, 6], hold = 3
Output: 5The table lists each sale day from day 3, because hold = 3.
| Sale day | Price | Eligible purchase days | Lowest eligible price | Profit |
|---|---|---|---|---|
| 3 | 3 | days 0 to 0 | 4 | -1 |
| 4 | 2 | days 0 to 1 | 1 | 1 |
| 5 | 6 | days 0 to 2 | 1 | 5 |
The best allowed trade buys on day 1 at price 1 and sells on day 5 at price 6, a profit of 5. The 9 on day 2 is out of reach: it is only 1 day after day 1, and hold is 3.
Input: prices = [5, 4, 3], hold = 1
Output: 0Prices only fall, so every trade loses money. The answer is 0, not a negative number.
Input: prices = [2, 9], hold = 2
Output: 0The history has 2 days, so no trade is 2 days apart. No trade is allowed, and the answer is 0.
1 ≤ prices.length ≤ 100,000 (days)1 ≤ prices[d] ≤ 1,000,000,000 (units)1 ≤ hold ≤ 100,000 (days)Trying every pair of days costs about n × n / 2 steps, 5 × 10^9 at n = 100,000. A sale can use any purchase that is old enough, and the best one is the cheapest of them. That cheapest price can be kept up to date as the sale day moves forward, so one pass is enough.