Best Time to Buy and Sell Stock IV
Pattern: Stock buy and sell
At most k transactions: keep buy[t] and sell[t] for t = 1..k. The t-th buy is paid from the money after t - 1 sales.
The problem
Return the most profit from at most k buy-then-sell transactions.
Think first
- How does problem III generalise?
- What does buy[t] depend on?
- What if k is at least n / 2?
Hints
Brute force, and why it fails
Try every set of k transactions: exponential.
The key insight
The stage you are in (how many buys and sells) is all the history that matters.
Dry run
k = 2, prices [2, 4, 1]. Buy at 2, sell at 4: 2.
Step 1 of 2
The plan
buy[t] = -inf; sell[t] = 0
for p: for t in 1..k: buy[t] = max(buy[t], sell[t-1] - p); sell[t] = max(sell[t], buy[t] + p)
return sell[k]
Complexity
- Time
O(n × k)- Space
O(k)
k pairs per day.
Edge cases
- k = 0: 0.
- Large k: as problem II.
- One day.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int maxProfit(int k, int[] prices) {
int[] buy = new int[k + 1], sell = new int[k + 1]; // buy[t]/sell[t]: money after the t-th buy / sale
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); // the t-th buy uses the money after t - 1 sales
sell[t] = Math.max(sell[t], buy[t] + p);
}
return sell[k];
}
}C++
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0); // money after the t-th buy / sale
for (int p : prices)
for (int t = 1; t <= k; t++) {
buy[t] = max(buy[t], sell[t - 1] - p); // the t-th buy uses the money after t - 1 sales
sell[t] = max(sell[t], buy[t] + p);
}
return sell[k];
}
};Python
class Solution:
def maxProfit(self, k: int, prices: list[int]) -> int:
buy, sell = [float("-inf")] * (k + 1), [0] * (k + 1) # money after the t-th buy / sale
for p in prices:
for t in range(1, k + 1):
buy[t] = max(buy[t], sell[t - 1] - p) # the t-th buy uses the money after t - 1 sales
sell[t] = max(sell[t], buy[t] + p)
return sell[k]Common mistakes
- Using sell[t] instead of sell[t - 1] for buy[t].
- Large memory for large k.