Parcel-delivery app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-309dp
A freight exchange lets a broker resell space on departing trucks, one slot at a time. The price of a slot is known for each day. The broker holds at most one slot at a time, and may buy or sell once a day.
After each sale, the exchange locks the broker out for pause days. The broker can not buy in those days. It wants the best total profit over any number of resales.
Write best_profit_with_pause(prices, pause).
prices[i] is the price of one slot on day i.s, you may not buy on the days s + 1 to s + pause. You may buy again on day s + pause + 1.0 when no trade pays.Input: prices = [4,9,3,10,5,12], pause = 1
Output: 12The solution keeps a table of the best profit when holding nothing at the end of each day. It also keeps one number for the best profit when holding a slot. A purchase on day i starts from the table value for day i - pause - 1, or from 0.
| Day | Price | Best profit holding nothing | Best profit holding one |
|---|---|---|---|
| 0 | 4 | 0 | -4 |
| 1 | 9 | 5 | -4 |
| 2 | 3 | 5 | -3 |
| 3 | 10 | 7 | -3 |
| 4 | 5 | 7 | 0 |
| 5 | 12 | 12 | 0 |
The trades are 4 to 9, then 5 to 12. The cheap day 2 is locked out after the sale on day 1.
Input: prices = [4,9,3,10,5,12], pause = 0
Output: 19With no lockout, the trades 4 to 9, 3 to 10 and 5 to 12 give 5 + 7 + 7.
Input: prices = [5,4,3], pause = 2
Output: 0The price only falls, so no trade pays.
1 ≤ len(prices) ≤ 100,0000 ≤ prices[i] ≤ 1,000,0000 ≤ pause ≤ 100,000Each day can double the number of plans, so 60 days are already over a quintillion. Yet a day depends only on whether you hold a slot, and on the best profit a few days back. That is a table of 100,000 numbers.