Best Time to Buy and Sell Stock IV
Best Time to Buy and Sell Stock IV is LeetCode 188 (Hard). You get an integer k and an array prices, where prices[i] is the price of one share on day i. Return the maximum profit from at most k transactions.
- A transaction is one buy followed later by one sell, and you can own only one share at a time.
- Using fewer than
ktrades, or none, is allowed.
With k at most 100 and at most 1000 days, a table that touches every (day, trade) pair once is only 10⁵ updates.
- 1 <= k <= 100
- 1 <= prices.length <= 1000
- 0 <= prices[i] <= 1000
Intuition
Number the trades 1 to k and keep two values for each one:
- buy[j]: the best balance after making the j-th buy.
- sell[j]: the best profit after making the j-th sell.
On each day, update every trade number. The j-th buy is paid for out of sell[j - 1], the profit of the first j − 1 finished trades, and the j-th sell closes it. Trade j can only start from what trade j − 1 earned, so the trades stay in order and never overlap. sell[0] stays 0, the profit of making no trade at all.
When a count of allowed actions is part of the input, add it as an index to the states you would use for one action. Each level reads only the level below it.
Approach
Take [1, 4, 2, 5] and work out the best profit with k = 1 and then with k = 2. Then ask what the second trade needs to know about the first one.
Make the two arrays
Create buy with k + 1 entries of minus infinity, since no buy has happened yet, and sell with k + 1 zeros. Index 0 stands for "no trade made yet" and stays 0.
The j-th buy
For each price, and for j from 1 to k, set buy[j] = max(buy[j], sell[j - 1] - price). You either keep an earlier j-th buy, or make it today using the profit of j - 1 finished trades.
The j-th sell
Then set sell[j] = max(sell[j], buy[j] + price). You either keep an earlier j-th sale or close trade j today. Reading the buy[j] set a moment ago allows a same-day buy and sell, which earns 0 and changes nothing.
Why the direction of the j loop does not matter
Going up, buy[j] reads today's sell[j - 1]; going down, it reads yesterday's. The only extra option today's value adds is selling and buying back on the same day at the same price, worth 0, so both orders give the same answer.
Return sell[k]
Each level can copy the one below through a same-day buy and sell, so sell[k] is never less than sell[j] for a smaller j. Plans that need fewer than k trades are already included.
Code in Python, C++ and Java
Common pitfalls
Dropping the index-0 sentinel
buy = [float("-inf")] * k
sell = [0] * k
for j in range(k):
buy[j] = max(buy[j], sell[j - 1] - price)buy = [float("-inf")] * (k + 1)
sell = [0] * (k + 1)
for j in range(1, k + 1):At j = 0, Python reads sell[-1], the last trade's profit, so the first trade can be funded by trades that come after it. With k = 1 on [1, 3, 1, 3] the trade feeds itself and the result is 4 instead of 2.
Starting every buy at 0
buy = [0] * (k + 1)
buy = [float("-inf")] * (k + 1)A buy of 0 is a share you never paid for, so the first price is counted as profit. On [5, 4] with k = 1 this returns 5; prices only fall, so the answer is 0.
Counting a trade on both the buy and the sell
def f(i, holding, left):
...
buy = -prices[i] + f(i + 1, True, left - 1)
sell = prices[i] + f(i + 1, False, left - 1) buy = -prices[i] + f(i + 1, True, left)
sell = prices[i] + f(i + 1, False, left - 1)In the recursive version a buy and its sell are one trade, so only one of them should use up a trade. Charging both halves the limit: with k = 2 on [1, 3, 1, 3] it returns 2 instead of 4.
Edge cases
k larger than the trades that fit, e.g. k = 100 on [1, 2, 3, 4, 5]The extra levels just copy the level below them, so sell[100] equals the best real plan, 4.
Every buy is followed only by a same-day sell, which earns 0, so the answer is 0.
Complexity
Best Time to Buy and Sell Stock IV FAQ
How is this different from Best Time to Buy and Sell Stock III?
Problem 123 is this problem with k = 2, and its four named variables are buy[1], sell[1], buy[2] and sell[2] here. With k = 1 the same code solves the one-trade problem as well.
Do I still need the k ≥ n / 2 shortcut?
Not with the current limits. A trade needs two days, so more than n / 2 trades can never all be used; past that point the answer is just the sum of every rise, which is why many solutions add that shortcut. With k at most 100 the arrays hold at most 101 entries, so the shortcut only saves a little time.