Online store~35 min2s · 256 MBtarget O(n × k) time, O(k) spacedp
A collectors' marketplace shows the daily price of one rare item. A reseller can hold one copy at a time. They buy it on a day, sell it on a later day, and that is one round trip. They can only afford k round trips before the season ends.
Looking back at the prices, the reseller wants to know the most profit that at most k round trips could have made. The trips must not overlap: a copy must be sold before the next one is bought.
Write best_profit_k_trips(prices, k).
prices[d] is the price of the item on day d.k trips, and may make none.Input: prices = [5, 2, 8, 4, 9, 1, 6], k = 2
Output: 12The table gives buy[j] and sell[j] after each day.
| Day | Price | buy[1] | sell[1] | buy[2] | sell[2] |
|---|---|---|---|---|---|
| 0 | 5 | -5 | 0 | -5 | 0 |
| 1 | 2 | -2 | 0 | -2 | 0 |
| 2 | 8 | -2 | 6 | -2 | 6 |
| 3 | 4 | -2 | 6 | 2 | 6 |
| 4 | 9 | -2 | 7 | 2 | 11 |
| 5 | 1 | -1 | 7 | 6 | 11 |
| 6 | 6 | -1 | 7 | 6 | 12 |
With k = 2, the best trips are buy at 2 on day 1 and sell at 9 on day 4, for a profit of 7. Then buy at 1 on day 5 and sell at 6 on day 6, for 5. The total is 12. The table shows the best balance while holding, and the best profit with no copy held.
Input: prices = [7, 6, 4, 3], k = 2
Output: 0Prices only fall, so no trip makes a profit. The answer is 0.
Input: prices = [1, 5], k = 3
Output: 4There is only one useful trip: buy at 1 and sell at 5. More trips cannot add profit.
1 ≤ prices.length ≤ 10,000 (days)1 ≤ prices[d] ≤ 1,000,000 (units)1 ≤ k ≤ 50 (round trips)The profit reaches about 10^10, so it needs a 64-bit result.
Trying every wait, buy and sell choice for every day costs about 2^n steps. The best profit after day d depends only on the trips used and on whether a copy is held. There are 2 × k such states, so a table over days and states costs about n × k steps, 5 × 10^5 at the limits.