LeetCode #188 Hard

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 k trades, 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.

Constraints
  • 1 <= k <= 100
  • 1 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000
dynamic-programmingarraystate-machine
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxProfit(self, k: int, prices: List[int]) -> int:
▶3 buy = [float("-inf")] * (k + 1)
▶4 sell = [0] * (k + 1)
▶5 for price in prices:
▶6 for j in range(1, k + 1):
▶7 buy[j] = max(buy[j], sell[j - 1] - price)
▶8 sell[j] = max(sell[j], buy[j] + price)
▶9 return sell[k]
price1day 04day 12day 25day 3buysellnone0trade 1−∞0trade 2−∞02 trades allowed: no buy made yet
k2
buyall −∞nothing bought
sellall 0
One row per trade. Row j holds the best balance after the j-th buy and the best profit after the j-th sell. Buys start at minus infinity because no share has been paid for; the top row, no trade at all, is fixed at 0.
price1day 04day 12day 25day 3buysellnone0trade 1−10try −1trade 2−∞0trade 1 buys at 1 from profit 0 → −1
day0price 1
buy[1]−1bought today
Trade 1 can only start from what no trades earned (0). Paying 1 out of that leaves −1, better than having no buy at all.
price1day 04day 12day 25day 3buysellnone0trade 1−10try 0trade 2−∞0trade 1 selling at 1 gives 0: keep 0
day0price 1
sell[1]0kept
Selling today makes 0, which does not beat 0. A same-day buy and sell earns nothing, so it ties.
price1day 04day 12day 25day 3buysellnone0trade 1−10trade 2−10try −1trade 2 buys at 1 from profit 0 → −1
day0price 1
buy[2]−1bought today
Trade 2 can only start from what the first 1 trade earned (0). Paying 1 out of that leaves −1, better than having no buy at all.
price1day 04day 12day 25day 3buysellnone0trade 1−10trade 2−10try 0trade 2 selling at 1 gives 0: keep 0
day0price 1
sell[2]0kept
Selling today makes 0, which does not beat 0. A same-day buy and sell earns nothing, so it ties.
price1day 04day 12day 25day 3buysellnone0trade 1−10try −4trade 2−10trade 1 buying at 4 gives −4: keep −1
day1price 4
buy[1]−1kept
Buying for trade 1 today leaves −4, worse than the buy already held (−1). Keeping the cheaper position means more profit when it sells.
price1day 04day 12day 25day 3buysellnone0trade 1−13try 3trade 2−10trade 1 sells at 4 → profit 3
day1price 4
sell[1]3sold today
Closing trade 1 at 4 gives a total of 3, the best so far with 1 trade. Trade 2 can now start from it.
price1day 04day 12day 25day 3buysellnone0trade 1−13trade 2−10try −1trade 2 buying at 4 gives −1: keep −1
day1price 4
buy[2]−1kept
Buying for trade 2 today leaves −1, worse than the buy already held (−1). Keeping the cheaper position means more profit when it sells.
price1day 04day 12day 25day 3buysellnone0trade 1−13trade 2−13try 3trade 2 sells at 4 → profit 3
day1price 4
sell[2]3sold today
Closing trade 2 at 4 gives a total of 3, the best so far with 2 trades. This row is the answer row.
price1day 04day 12day 25day 3buysellnone0trade 1−13try −2trade 2−13trade 1 buying at 2 gives −2: keep −1
day2price 2
buy[1]−1kept
Buying for trade 1 today leaves −2, worse than the buy already held (−1). Keeping the cheaper position means more profit when it sells.
price1day 04day 12day 25day 3buysellnone0trade 1−13try 1trade 2−13trade 1 selling at 2 gives 1: keep 3
day2price 2
sell[1]3kept
Selling today makes 1, which does not beat 3.
price1day 04day 12day 25day 3buysellnone0trade 1−13trade 213try 1trade 2 buys at 2 from profit 3 → 1
day2price 2
buy[2]1bought today
Trade 2 can only start from what the first 1 trade earned (3). Paying 2 out of that leaves 1, better than the earlier buy (−1).
price1day 04day 12day 25day 3buysellnone0trade 1−13trade 213try 3trade 2 selling at 2 gives 3: keep 3
day2price 2
sell[2]3kept
Selling today makes 3, which does not beat 3. A same-day buy and sell earns nothing, so it ties.
price1day 04day 12day 25day 3buysellnone0trade 1−13try −5trade 213trade 1 buying at 5 gives −5: keep −1
day3price 5
buy[1]−1kept
Buying for trade 1 today leaves −5, worse than the buy already held (−1). Keeping the cheaper position means more profit when it sells.
price1day 04day 12day 25day 3buysellnone0trade 1−14try 4trade 213trade 1 sells at 5 → profit 4
day3price 5
sell[1]4sold today
Closing trade 1 at 5 gives a total of 4, the best so far with 1 trade. Trade 2 can now start from it.
price1day 04day 12day 25day 3buysellnone0trade 1−14trade 213try −1trade 2 buying at 5 gives −1: keep 1
day3price 5
buy[2]1kept
Buying for trade 2 today leaves −1, worse than the buy already held (1). Keeping the cheaper position means more profit when it sells.
price1day 04day 12day 25day 3buysellnone0trade 1−14trade 216try 6trade 2 sells at 5 → profit 6
day3price 5
sell[2]6sold today
Closing trade 2 at 5 gives a total of 6, the best so far with 2 trades. This row is the answer row.
price1buy 04sell 12buy 25sell 3buysellnone0trade 1−14trade 216answer: 6
sell[2]6
trades used2
Answer 6. The last row holds the best profit with at most 2 trades; the plan is marked in the price row.
05

Common pitfalls

Dropping the index-0 sentinel

✗ Wrong
buy = [float("-inf")] * k
sell = [0] * k
for j in range(k):
    buy[j] = max(buy[j], sell[j - 1] - price)
✓ Right
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

✗ Wrong
buy = [0] * (k + 1)
✓ Right
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

✗ Wrong
def f(i, holding, left):
    ...
    buy = -prices[i] + f(i + 1, True, left - 1)
    sell = prices[i] + f(i + 1, False, left - 1)
✓ Right
    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.

06

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.

A single day

Every buy is followed only by a same-day sell, which earns 0, so the answer is 0.

07

Complexity

Time
O(n · k)
Space
O(k)
Every day updates both values for each of the k trades. Only the two arrays of length k + 1 are stored, not a full days-by-trades table.
08

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.