15% off all plans & roadmaps Use code
See plansBest Time to Buy and Sell Stock IV
- LeetCode 188
- Hard
- Dynamic Programming (DP) Patterns
- Stock problems
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 <= 1000 <= prices.length <= 10000 <= 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.
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.
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
- Write solve(day, kLeft, holding) that returns the best profit from that day onward.
- Return 0 when the days run out or kLeft is 0.
- Always consider skipping today with solve(day + 1, kLeft, holding).
- If holding, also consider selling: prices[day] + solve(day + 1, kLeft - 1, false).
- If not holding, also consider buying: -prices[day] + solve(day + 1, kLeft, true).
- 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
| Time | O(2^n) |
|---|---|
| Space | O(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)JavaTested in our runner
class Solution {
public int maxProfit(int k, int[] prices) {
return solve(prices, 0, k, false);
}
// Best profit from day onward, given transactions left and whether we hold a share.
private int solve(int[] prices, int day, int kLeft, boolean holding) {
if (day == prices.length || kLeft == 0) return 0;
int skip = solve(prices, day + 1, kLeft, holding);
if (holding) {
return Math.max(skip, prices[day] + solve(prices, day + 1, kLeft - 1, false));
}
return Math.max(skip, -prices[day] + solve(prices, day + 1, kLeft, true));
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
return solve(prices, 0, k, false);
}
private:
// Best profit from day onward, given transactions left and whether we hold a share.
int solve(vector<int>& prices, int day, int kLeft, bool holding) {
if (day == (int)prices.size() || kLeft == 0) return 0;
int skip = solve(prices, day + 1, kLeft, holding);
if (holding) {
return max(skip, prices[day] + solve(prices, day + 1, kLeft - 1, false));
}
return max(skip, -prices[day] + solve(prices, day + 1, kLeft, true));
}
};JavaScriptTested in our runner
var maxProfit = function(k, prices) {
const n = prices.length;
// Best profit from day onward, given transactions left and whether we hold a share.
const solve = (day, kLeft, holding) => {
if (day === n || kLeft === 0) return 0;
const skip = solve(day + 1, kLeft, holding);
if (holding) {
return Math.max(skip, prices[day] + solve(day + 1, kLeft - 1, false));
}
return Math.max(skip, -prices[day] + solve(day + 1, kLeft, true));
};
return solve(0, k, false);
};GoTested in our runner
func maxProfit(k int, prices []int) int {
n := len(prices)
var solve func(day, kLeft int, holding bool) int
solve = func(day, kLeft int, holding bool) int {
if day == n || kLeft == 0 {
return 0
}
skip := solve(day+1, kLeft, holding)
if holding {
return max2(skip, prices[day]+solve(day+1, kLeft-1, false))
}
return max2(skip, -prices[day]+solve(day+1, kLeft, true))
}
return solve(0, k, false)
}
func max2(a, b int) int {
if a > b {
return a
}
return b
}C#Tested in our runner
public class Solution {
public int maxProfit(int k, int[] prices) {
return Solve(prices, 0, k, false);
}
// Best profit from day onward, given transactions left and whether we hold a share.
private int Solve(int[] prices, int day, int kLeft, bool holding) {
if (day == prices.Length || kLeft == 0) return 0;
int skip = Solve(prices, day + 1, kLeft, holding);
if (holding) {
return Math.Max(skip, prices[day] + Solve(prices, day + 1, kLeft - 1, false));
}
return Math.Max(skip, -prices[day] + Solve(prices, day + 1, kLeft, true));
}
}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 infographicSolution pattern
Stock problems
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
- If k is at least n // 2, add every positive difference prices[i] - prices[i - 1] and return the total.
- Otherwise create buy with k + 1 entries set to a very small number, and sell with k + 1 zeros.
- For each price in order, loop j from 1 to k.
- Set buy[j] to the larger of buy[j] and sell[j - 1] - price.
- Set sell[j] to the larger of sell[j] and buy[j] + price.
- 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.
| Day | Price | buy[1] | sell[1] | buy[2] | sell[2] |
|---|---|---|---|---|---|
| start | - | -inf | 0 | -inf | 0 |
| 1 | 3 | -3 | 0 | -3 | 0 |
| 2 | 2 | -2 | 0 | -2 | 0 |
| 3 | 6 | -2 | 4 | -2 | 4 |
| 4 | 5 | -2 | 4 | -1 | 4 |
| 5 | 0 | 0 | 4 | 4 | 4 |
| 6 | 3 | 0 | 4 | 4 | 7 |
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
| Time | O(n * k), or O(n) when k >= n // 2 |
|---|---|
| Space | O(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]JavaTested in our runner
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
// With k >= n / 2 the limit never binds, so take every rise.
if (k >= n / 2) {
int profit = 0;
for (int i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
final int NEG = -1000000000;
int[] buy = new int[k + 1];
int[] sell = new int[k + 1];
for (int j = 0; j <= k; j++) buy[j] = NEG;
for (int price : prices) {
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - price);
sell[j] = Math.max(sell[j], buy[j] + price);
}
}
return sell[k];
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
// With k >= n / 2 the limit never binds, so take every rise.
if (k >= n / 2) {
int profit = 0;
for (int i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
const int NEG = -1000000000;
vector<int> buy(k + 1, NEG);
vector<int> sell(k + 1, 0);
for (int price : prices) {
for (int j = 1; j <= k; j++) {
buy[j] = max(buy[j], sell[j - 1] - price);
sell[j] = max(sell[j], buy[j] + price);
}
}
return sell[k];
}
};JavaScriptTested in our runner
var maxProfit = function(k, prices) {
const n = prices.length;
// With k >= n / 2 the limit never binds, so take every rise.
if (k >= Math.floor(n / 2)) {
let profit = 0;
for (let i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
const NEG = -1000000000;
const buy = new Array(k + 1).fill(NEG);
const sell = new Array(k + 1).fill(0);
for (const price of prices) {
for (let j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - price);
sell[j] = Math.max(sell[j], buy[j] + price);
}
}
return sell[k];
};GoTested in our runner
func maxProfit(k int, prices []int) int {
n := len(prices)
// With k >= n/2 the limit never binds, so take every rise.
if k >= n/2 {
profit := 0
for i := 1; i < n; i++ {
if prices[i] > prices[i-1] {
profit += prices[i] - prices[i-1]
}
}
return profit
}
const negInf = -1000000000
buy := make([]int, k+1)
sell := make([]int, k+1)
for j := range buy {
buy[j] = negInf
}
for _, price := range prices {
for j := 1; j <= k; j++ {
buy[j] = max2(buy[j], sell[j-1]-price)
sell[j] = max2(sell[j], buy[j]+price)
}
}
return sell[k]
}
func max2(a, b int) int {
if a > b {
return a
}
return b
}C#Tested in our runner
public class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.Length;
// With k >= n / 2 the limit never binds, so take every rise.
if (k >= n / 2) {
int profit = 0;
for (int i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
const int NEG = -1000000000;
int[] buy = new int[k + 1];
int[] sell = new int[k + 1];
for (int j = 0; j <= k; j++) buy[j] = NEG;
foreach (int price in prices) {
for (int j = 1; j <= k; j++) {
buy[j] = Math.Max(buy[j], sell[j - 1] - price);
sell[j] = Math.Max(sell[j], buy[j] + price);
}
}
return sell[k];
}
}Common mistakes
- Initialising
buyto 0 instead of a very small number. A zero start makes buying look free, so the DP skips the real cost. Start everybuy[j]at a large negative value. - Looping
jfrom 0 in the inner loop, which readsbuy[0]. Start j at 1 and treatsell[0] = 0as the base case with no transactions used. - Returning
buy[k]instead ofsell[k]. Abuyvalue 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 / 2shortcut 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 stalebuy[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 = 1with[1, 2, 3, 4, 5]: return 4, one buy on day 1 and one sell on day 5.- Maximum size,
k = 100and 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
Related problems
- Best Time to Buy and Sell Stock III · same technique: Stock problems
- Best Time to Buy and Sell Stock with Cooldown · same technique: Stock problems
- Best Time to Buy and Sell Stock II · same technique: Stock problems
- Best Time to Buy and Sell Stock · same technique: Stock problems
- Distinct Subsequences · same pattern: Dynamic Programming (DP) Patterns
- Burst Balloons · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Path in a Matrix · same pattern: Dynamic Programming (DP) Patterns
- Regular Expression Matching · same pattern: Dynamic Programming (DP) Patterns
- Word Break II · same pattern: Dynamic Programming (DP) Patterns
- Stone Game III · same pattern: Dynamic Programming (DP) Patterns