Best Time to Buy and Sell Stock IV
Best Time to Buy and Sell Stock IV is a hard dynamic programming problem solved with the state machine dp - stock problems pattern.
The best approach, optimal (unlimited-trades shortcut, then the arrays), runs in O(n · min(k, n)) time and O(min(k, n)) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from memoized recursion (day, trades left, holding) up.
Problem
You are given an integer k and an array prices, where prices[i] is the price of a stock on day i.
A transaction is one buy followed later by one sell. You may make at most k transactions, and you can hold at most one share at a time, so you must sell the share you own before buying again.
Return the largest total profit you can make. If no transaction can earn anything, return 0.
Examples
Example 1
- Input
k = 1, prices = [5,2,8,3,9]- Output
7- Why
- With a single trade, the best is to buy at 2 on day 1 and sell at 9 on day 4, earning 7.
Example 2
- Input
k = 2, prices = [5,2,8,3,9]- Output
12- Why
- A second trade lets you also catch the dip: buy at 2 and sell at 8 (profit 6), then buy at 3 and sell at 9 (profit 6), for 12 in total.
Example 3
- Input
k = 2, prices = [1,4,2,6,3,8]- Output
10- Why
- There are three rises, but only two trades are allowed. Buying at 1 and selling at 6 (profit 5), then buying at 3 and selling at 8 (profit 5) gives 10, more than any other pair of trades.
Constraints
1 <= k <= 1001 <= prices.length <= 10000 <= prices[i] <= 1000
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 19 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Memoized recursion (day, trades left, holding) | O(n · k) | O(n · k) |
| Bottom-up buy and sell arrays | O(n · k) | O(k) |
| Optimal (unlimited-trades shortcut, then the arrays) | O(n · min(k, n)) | O(min(k, n)) |
1Memoized recursion (day, trades left, holding)
O(n · k)There are n × (k + 1) × 2 states, and each one is computed once with O(1) work.O(n · k)The memo table has n × (k + 1) × 2 entries, and the recursion goes n calls deep.Describe a moment by three numbers: the day, how many trades you may still finish, and whether you are holding a share. From there you can skip the day, keeping the same state for tomorrow, or act: if you hold nothing you may buy (pay prices[day], now holding), and if you hold a share you may sell (gain prices[day], one trade fewer left, not holding). The best profit from a state is the larger of skipping and acting. Days run out or trades run out → nothing more to earn. There are only n × (k + 1) × 2 states, so remembering each answer makes the recursion fast.
- dfs(day, left, holding) = 0 if day == n or left == 0.
- skip = dfs(day + 1, left, holding).
- If holding: act = prices[day] + dfs(day + 1, left - 1, 0). Otherwise: act = -prices[day] + dfs(day + 1, left, 1).
- Store and return max(skip, act); the answer is dfs(0, k, 0).
class Solution {
private int[] prices;
private Integer[][][] memo;
public int maxProfit(int k, int[] prices) {
this.prices = prices;
memo = new Integer[prices.length][k + 1][2];
return dfs(0, k, 0);
}
private int dfs(int day, int left, int holding) {
if (day == prices.length || left == 0) return 0;
if (memo[day][left][holding] != null) return memo[day][left][holding];
int skip = dfs(day + 1, left, holding);
int act;
if (holding == 1) act = prices[day] + dfs(day + 1, left - 1, 0);
else act = -prices[day] + dfs(day + 1, left, 1);
return memo[day][left][holding] = Math.max(skip, act);
}
}class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
sys.setrecursionlimit(10000)
n = len(prices)
memo = [[[None] * 2 for _ in range(k + 1)] for _ in range(n)]
def dfs(day, left, holding):
if day == n or left == 0:
return 0
if memo[day][left][holding] is not None:
return memo[day][left][holding]
skip = dfs(day + 1, left, holding)
if holding == 1:
act = prices[day] + dfs(day + 1, left - 1, 0)
else:
act = -prices[day] + dfs(day + 1, left, 1)
memo[day][left][holding] = max(skip, act)
return memo[day][left][holding]
return dfs(0, k, 0)class Solution {
vector<int> prices;
vector<vector<array<int, 2>>> memo;
int dfs(int day, int left, int holding) {
if (day == (int) prices.size() || left == 0) return 0;
if (memo[day][left][holding] != -1) return memo[day][left][holding];
int skip = dfs(day + 1, left, holding);
int act;
if (holding == 1) act = prices[day] + dfs(day + 1, left - 1, 0);
else act = -prices[day] + dfs(day + 1, left, 1);
return memo[day][left][holding] = max(skip, act);
}
public:
int maxProfit(int k, vector<int>& prices) {
this->prices = prices;
memo.assign(prices.size(), vector<array<int, 2>>(k + 1, {-1, -1}));
return dfs(0, k, 0);
}
};function maxProfit(k, prices) {
const n = prices.length;
const memo = new Map();
const dfs = (day, left, holding) => {
if (day === n || left === 0) return 0;
const key = (day * (k + 1) + left) * 2 + holding;
if (memo.has(key)) return memo.get(key);
const skip = dfs(day + 1, left, holding);
let act;
if (holding === 1) act = prices[day] + dfs(day + 1, left - 1, 0);
else act = -prices[day] + dfs(day + 1, left, 1);
const best = Math.max(skip, act);
memo.set(key, best);
return best;
};
return dfs(0, k, 0);
}2Bottom-up buy and sell arrays
O(n · k)For each of the n prices, the inner loop updates k pairs of states.O(k)Two arrays of k + 1 values; the days are not stored.Turn the recursion around and walk the days forward. For each trade number t from 1 to k keep two values: buy[t], the most cash you can have while holding the share of trade t, and sell[t], the most cash after finishing t trades. On each price p, trade t can start only after trade t - 1 has finished, so buy[t] = max(buy[t], sell[t - 1] - p), and finishing it gives sell[t] = max(sell[t], buy[t] + p). sell[0] stays 0 (no trades, no cash) and every buy starts at minus infinity, because you cannot hold a share before buying one. Since every value only grows, sell[k] at the end is the best profit with at most k trades. This is exactly the four-state machine for two trades, stretched to k pairs of states.
- buy[1..k] = minus infinity, sell[0..k] = 0.
- For each price p, for t = 1 to k: buy[t] = max(buy[t], sell[t - 1] - p), then sell[t] = max(sell[t], buy[t] + p).
- Return sell[k].
class Solution {
public int maxProfit(int k, int[] prices) {
int[] buy = new int[k + 1], sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE);
for (int p : prices) {
for (int t = 1; t <= k; t++) {
buy[t] = Math.max(buy[t], sell[t - 1] - p);
sell[t] = Math.max(sell[t], buy[t] + p);
}
}
return sell[k];
}
}class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
buy = [-math.inf] * (k + 1)
sell = [0] * (k + 1)
for p in prices:
for t in range(1, k + 1):
buy[t] = max(buy[t], sell[t - 1] - p)
sell[t] = max(sell[t], buy[t] + p)
return sell[k]class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0);
for (int p : prices) {
for (int t = 1; t <= k; t++) {
buy[t] = max(buy[t], sell[t - 1] - p);
sell[t] = max(sell[t], buy[t] + p);
}
}
return sell[k];
}
};function maxProfit(k, prices) {
const buy = new Array(k + 1).fill(-Infinity);
const sell = new Array(k + 1).fill(0);
for (const p of prices) {
for (let t = 1; t <= k; t++) {
buy[t] = Math.max(buy[t], sell[t - 1] - p);
sell[t] = Math.max(sell[t], buy[t] + p);
}
}
return sell[k];
}3Optimal (unlimited-trades shortcut, then the arrays)
O(n · min(k, n))The shortcut is one pass; the arrays run only when k < n / 2, costing O(n · k) there.O(min(k, n))The shortcut needs O(1); the arrays have k + 1 entries, and k < n / 2 whenever they are built.A trade needs a buy day and a later sell day, so n days can hold at most n / 2 useful trades. In fact the unlimited best, adding up every rise prices[i] - prices[i - 1] > 0, uses one trade per run of rising days, and those runs never share a day, so it never needs more than n / 2 trades. When k >= n / 2 the limit cannot bind: return the sum of the rises in O(n). Otherwise k < n / 2 and the buy and sell arrays run in O(n · k). This matters when k is huge compared with the number of days; it also keeps the inner loop from doing work that can never pay off.
- If 2k >= n: return the sum of max(0, prices[i] - prices[i - 1]) over i = 1 to n - 1.
- Otherwise run the buy and sell arrays for t = 1 to k and return sell[k].
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (2 * k >= n) {
int total = 0;
for (int i = 1; i < n; i++) total += Math.max(0, prices[i] - prices[i - 1]);
return total;
}
int[] buy = new int[k + 1], sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE);
for (int p : prices) {
for (int t = 1; t <= k; t++) {
buy[t] = Math.max(buy[t], sell[t - 1] - p);
sell[t] = Math.max(sell[t], buy[t] + p);
}
}
return sell[k];
}
}class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
if 2 * k >= n:
total = 0
for i in range(1, n):
total += max(0, prices[i] - prices[i - 1])
return total
buy = [-math.inf] * (k + 1)
sell = [0] * (k + 1)
for p in prices:
for t in range(1, k + 1):
buy[t] = max(buy[t], sell[t - 1] - p)
sell[t] = max(sell[t], buy[t] + p)
return sell[k]class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if (2 * k >= n) {
int total = 0;
for (int i = 1; i < n; i++) total += max(0, prices[i] - prices[i - 1]);
return total;
}
vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0);
for (int p : prices) {
for (int t = 1; t <= k; t++) {
buy[t] = max(buy[t], sell[t - 1] - p);
sell[t] = max(sell[t], buy[t] + p);
}
}
return sell[k];
}
};function maxProfit(k, prices) {
const n = prices.length;
if (2 * k >= n) {
let total = 0;
for (let i = 1; i < n; i++) total += Math.max(0, prices[i] - prices[i - 1]);
return total;
}
const buy = new Array(k + 1).fill(-Infinity);
const sell = new Array(k + 1).fill(0);
for (const p of prices) {
for (let t = 1; t <= k; t++) {
buy[t] = Math.max(buy[t], sell[t - 1] - p);
sell[t] = Math.max(sell[t], buy[t] + p);
}
}
return sell[k];
}Edge cases to test
- A single day: no trade can be completed, so the answer is 0
- Prices that only fall (or stay flat): every trade loses, so the answer is 0
- k larger than the number of rises: the limit no longer matters, and the answer is the sum of every upward step
- k = 1: the classic single trade, lowest price before the highest later price
- Two rises separated by a small dip with k = 1: one long trade across the dip beats either short one
- Equal prices on neighbouring days never add profit
Hints
Hint 1
On any day you are in one of two situations: holding a share or not. Together with how many trades you still may finish, that is the whole state.
Hint 2
From a state you either do nothing today, or act: buy if you hold nothing, sell if you hold a share. Count a trade as used when you sell.
Hint 3
Keep, for every t from 1 to k, the best cash while holding the share of trade t, and the best cash after finishing t trades. Each day, update them in order of t.
Hint 4
With n days, at most n / 2 trades can ever be useful. If k is at least that, simply add up every rise from one day to the next.
FAQ
What is the best time complexity for Best Time to Buy and Sell Stock IV?
Optimal (unlimited-trades shortcut, then the arrays) runs in O(n · min(k, n)) time and O(min(k, n)) extra space. The shortcut is one pass; the arrays run only when k < n / 2, costing O(n · k) there.
Which pattern does Best Time to Buy and Sell Stock IV use?
It is a dynamic programming problem that uses the state machine dp - stock problems pattern. Other problems with the same pattern: Best Time to Buy and Sell Stock, Best Time to Buy and Sell Stock II, Best Time to Buy and Sell Stock with Transaction Fee.
Is there a brute force solution for Best Time to Buy and Sell Stock IV?
Yes. Memoized recursion (day, trades left, holding) takes O(n · k) time and O(n · k) space. Describe a moment by three numbers: the day, how many trades you may still finish, and whether you are holding a share.
Which edge cases should I test for Best Time to Buy and Sell Stock IV?
A single day: no trade can be completed, so the answer is 0; Prices that only fall (or stay flat): every trade loses, so the answer is 0; k larger than the number of rises: the limit no longer matters, and the answer is the sum of every upward step; k = 1: the classic single trade, lowest price before the highest later price; Two rises separated by a small dip with k = 1: one long trade across the dip beats either short one; Equal prices on neighbouring days never add profit.