15% off all plans & roadmaps Use code

See plans

Best Time to Buy and Sell Stock IV

Updated

TL;DR: You may make at most k buy and sell trades on a price list, and you must sell before buying again. Track the best profit for each transaction count while you scan the prices once. That turns an exponential search into an O(n * k) table.

Problem

You get an integer array prices, where prices[i] is the price of a stock on day i. You also get an integer k.

Find the maximum profit you can make using at most k transactions. One transaction is one buy followed by one sell.

Note: You cannot hold more than one share at a time. You must sell before you buy again.

Example 1

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 at price 2 and sell on day 2 at price 4. Profit = 4 - 2 = 2.

Example 2

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 at price 2 and sell on day 3 at price 6. Profit = 6 - 2 = 4. Then buy on day 5 at price 0 and sell on day 6 at price 3. Profit = 3 - 0 = 3.

Constraints

  • 0 <= k <= 100
  • 0 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000

Constraints that matter

  • prices.length up to 1000 rules out any search over all trade sequences, which grows exponentially in the number of days.
  • k up to 100 means a DP table with k states per day is small enough to fill directly.
  • When k is at least half the number of days, the limit can never bind, so the problem reduces to summing every rise.
  • prices[i] between 0 and 1000 keeps every profit inside a plain 32-bit integer, so overflow is not a concern.

View on LeetCode

Hints

Hint 1

This is a dynamic programming problem over a small state machine.

Hint 2

The beginner version tries every possible plan.

Solution

Intuition

This is a dynamic programming problem over a small state machine. On any day you hold either a share or cash, and you have used some number of transactions so far. That gives only about 2 * k states per day, so you can track the best profit in each one.

Picture a row of labeled jars, one per transaction count, each holding only the best running total so far. The buy array is the jar for holding a share, and the sell array is the jar for holding cash.

The signal to look for is that the future depends on the current state, not on the full history of trades. Yesterday's best profit for each state is enough to compute today's. When a problem has this shape, process the array one element at a time and keep only the latest values.

For transaction count j, the best holding profit today is either the old holding profit or the best cash profit after j - 1 transactions minus today's price. The best cash profit is either the old cash profit or the best holding profit plus today's price. Taking the maximum at each step keeps the best path into every state, so the value for k is exact.

Watch the pattern animation

Worked example

Input: k = 2, prices = [3, 2, 6, 5, 0, 3]
Output: 7
Explanation: The best plan uses both transactions. Buying at 2 and selling at 6 gives 4. Buying at 0 and selling at 3 gives 3. The total is 7.

Approach 1: Brute force recursion

The beginner version tries every possible plan. On each day you can skip, buy if you hold nothing, or sell if you hold a share. Each sell uses one of the k transactions. The recursion tries every choice on every day and keeps the best total.

What is slow: the search solves the same state again and again through different paths. A state is the day, the transactions left and the holding flag. Every day adds a branch, so the number of paths roughly doubles with each day. With 1000 days this cannot finish.

Steps

  1. Write solve(day, kLeft, holding) that returns the best profit from that day onward.
  2. Return 0 when the days run out or kLeft is 0.
  3. Always consider skipping today with solve(day + 1, kLeft, holding).
  4. If holding, also consider selling: prices[day] + solve(day + 1, kLeft - 1, false).
  5. If not holding, also consider buying: -prices[day] + solve(day + 1, kLeft, true).
  6. Return solve(0, k, false).

Dry run

Start with solve(0, 2, no stock). The search branches on every day, so it explores many plans. One of them buys at 2 on day 1, sells at 6 on day 2, buys at 0 on day 4 and sells at 3 on day 5. That plan earns -2 + 6 - 0 + 3 = 7.

Other branches include selling at 5 on day 3 or buying at 3 on day 0. None of them beats 7, so the root returns 7, which is the expected output. The search reaches that plan only after exploring many dead ends that repeat the same states.

Complexity

TimeO(2^n)
SpaceO(n)

Let n be the number of days. Each call makes at most two recursive calls, one for skipping and one for the action, so the call tree has about 2^n nodes in the worst case. The recursion never goes deeper than n levels, and each level holds one stack frame, so the extra space is O(n). Nothing is cached, so the repeated states are solved again every time.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        n = len(prices)

        def solve(day: int, k_left: int, holding: bool) -> int:
            # Out of days or out of transactions: no more profit is possible.
            if day == n or k_left == 0:
                return 0
            skip = solve(day + 1, k_left, holding)
            if holding:
                # Selling uses one transaction.
                return max(skip, prices[day] + solve(day + 1, k_left - 1, False))
            # Buying does not use a transaction until the sale.
            return max(skip, -prices[day] + solve(day + 1, k_left, True))

        return solve(0, k, False)

The Stock problems infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Stock problems

Part of Dynamic Programming (DP) Patterns

Approach 2: One-pass DP over buy and sell arraysOptimalStock problems

What is slow: the brute force solves the same (day, transactions used, holding) state many times. Each state depends only on the previous day, so the day dimension is not needed. Keep only the latest values.

The insight: keep two arrays of length k + 1. buy[j] is the best profit after starting transaction j while holding a share. sell[j] is the best profit after finishing transaction j while holding cash. Scan the prices once, and for each price update j from 1 to k.

When k is at least n // 2, the limit never binds. Then you can take every rise between adjacent days and skip the table.

Why it is correct. After each price, buy[j] holds the best profit achievable so far with j transactions started and a share in hand. Each update reads only the previous day's values for one neighboring state, so keeping the maximum per state never discards a better path. So when the last price is processed, sell[k] is the best cash profit over every allowed set of at most k trades.

Steps

  1. If k is at least n // 2, add every positive difference prices[i] - prices[i - 1] and return the total.
  2. Otherwise create buy with k + 1 entries set to a very small number, and sell with k + 1 zeros.
  3. For each price in order, loop j from 1 to k.
  4. Set buy[j] to the larger of buy[j] and sell[j - 1] - price.
  5. Set sell[j] to the larger of sell[j] and buy[j] + price.
  6. After the last price, return sell[k].

Dry run

The shortcut does not apply here, because k = 2 is less than n // 2 = 3, so the table is built. Each row shows the state after one price. Start with buy = [-inf, -inf, -inf] and sell = [0, 0, 0], and track entries 1 and 2.

DayPricebuy[1]sell[1]buy[2]sell[2]
start--inf0-inf0
13-30-30
22-20-20
36-24-24
45-24-14
500444
630447

On day 3, sell[1] becomes -2 + 6 = 4. On day 5, buy[2] becomes sell[1] - 0 = 4, the profit from the first trade used to start the second. On day 6, sell[2] becomes 4 + 3 = 7, which matches the expected output.

Complexity

TimeO(n * k), or O(n) when k >= n // 2
SpaceO(k), or O(1) in the shortcut case

Let n be the number of days. The DP visits each price once and runs an inner loop of k steps, so it does n * k updates. The shortcut scans the array once, which is n - 1 comparisons. The two arrays hold k + 1 numbers each, so the DP uses O(k) space, and the shortcut uses only a few variables.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        n = len(prices)
        # With k >= n // 2 the limit never binds, so take every rise.
        if k >= n // 2:
            return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, n))

        # buy[j]: best profit after starting transaction j (holding a share).
        # sell[j]: best profit after finishing transaction j (holding cash).
        buy = [float('-inf')] * (k + 1)
        sell = [0] * (k + 1)

        for price in prices:
            for j in range(1, k + 1):
                buy[j] = max(buy[j], sell[j - 1] - price)
                sell[j] = max(sell[j], buy[j] + price)

        return sell[k]

Common mistakes

  • Initialising buy to 0 instead of a very small number. A zero start makes buying look free, so the DP skips the real cost. Start every buy[j] at a large negative value.
  • Looping j from 0 in the inner loop, which reads buy[0]. Start j at 1 and treat sell[0] = 0 as the base case with no transactions used.
  • Returning buy[k] instead of sell[k]. A buy value means a share is still held, so the transaction is unfinished and its profit is not yet banked.
  • Summing only prices[n - 1] - prices[0] in the shortcut. The unlimited case needs every rise added, so [1, 5, 2, 6] gives 4 + 4 = 8, not 5.
  • Skipping the k >= n / 2 shortcut and allocating arrays sized by a huge k such as 10^9. The shortcut keeps the table small and the run fast.
  • Updating sell[j] with a stale buy[j] in a separate pass, so the sell uses an old price. Update buy first, then sell, within the same j step.

Edge cases

  • Empty prices: return 0, because there is no day to trade on.
  • k = 0: return 0, because no transaction is allowed.
  • One day, such as prices = [5] with k = 3: return 0, because a sale needs a later day.
  • Strictly falling prices, such as [5, 4, 3]: return 0, since no buy can be followed by a higher sell.
  • Flat prices, such as [7, 7, 7]: return 0, since every trade earns nothing.
  • k = 1 with [1, 2, 3, 4, 5]: return 4, one buy on day 1 and one sell on day 5.
  • Maximum size, k = 100 and 1000 random prices up to 1000: the DP runs about 10^5 updates and stays fast.

Follow-ups interviewers ask

What if there is no limit on the number of transactions?
The limit disappears, so you take every rise. Add max(0, prices[i] - prices[i - 1]) for each day. That runs in O(n) time and O(1) space, and it is the same rule the shortcut uses.
Can you solve it in O(1) extra space for any k?
Not with this method. The DP needs one buy value and one sell value per transaction count, so the space is O(k). The O(1) case only applies when k is at least n // 2, where the rise-sum rule works.
What if every sale costs a fixed fee?
Subtract the fee when you sell. The sell update becomes sell[j] = max(sell[j], buy[j] + price - fee). The buy update and the loop order stay the same.

Best Time to Buy and Sell Stock IV FAQ

What is the time complexity of Best Time to Buy and Sell Stock IV?

The DP runs in O(n * k) time when k is below n // 2. When k is at least n // 2, the rise-sum shortcut runs in O(n) time. The brute force recursion takes O(2^n) time.

Why use dynamic programming for Best Time to Buy and Sell Stock IV?

Each day depends only on the best profit for each state on the previous day. The DP keeps those few values and drops the repeated work in the recursion. That turns an exponential search into n * k updates.

Can Best Time to Buy and Sell Stock IV be solved in O(1) extra space?

Not in general. The DP needs one buy value and one sell value for each transaction count, so it uses O(k) space. When k is at least n // 2, the rise-sum shortcut uses O(1) space.

How is Best Time to Buy and Sell Stock IV different from Stock II?

Stock II has no transaction limit, so you take every rise. Stock IV caps the number of transactions at k. When k is at least n // 2, the cap does not matter and the Stock II rule applies.

Why does the Python version start buy with float('-inf') but still return an int?

The first update replaces each buy value with a real integer, since sell[j - 1] - price is an int. The sell values start at 0 and only take integer values, so sell[k] is an int.

Asked at

See which companies ask this — Pro

Practise it