188. Best Time to Buy and Sell Stock IV
Asked at 12Apple30Google27Amazon24Microsoft20Meta8.5Infosys30PubMatic100HashedIn62Citadel47Visa39Goldman Sachs36TikTok35
Problem
prices[i] is a stock's price on day i. Make at most k buy-then-sell transactions (holding at most one share at a time) and return the maximum profit.
Example: k = 2, prices = [3,2,6,5,0,3] → 7
Constraints: k ≤ 100; n ≤ 1000.
Generalize 123 to k transactions: arrays buy[1..k], sell[1..k]; buy[j] = max(buy[j], sell[j−1] − p), sell[j] = max(sell[j], buy[j] + p). If k ≥ n/2 it's unlimited (sum of rises).
Complexity: O(n·k).
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
if k >= len(prices) // 2:
return sum(max(0, b - a) for a, b in zip(prices, prices[1:]))
buy = [float("-inf")] * (k + 1)
sell = [0] * (k + 1)
for p in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - p)
sell[j] = max(sell[j], buy[j] + p)
return sell[k]
assert Solution().maxProfit(2, [2, 4, 1]) == 2
assert Solution().maxProfit(2, [3, 2, 6, 5, 0, 3]) == 7
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (k >= n / 2) {
int s = 0;
for (int i = 1; i < n; i++) s += Math.max(0, prices[i] - prices[i - 1]);
return s;
}
int[] buy = new int[k + 1], sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE / 2);
for (int p : prices)
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - p);
sell[j] = Math.max(sell[j], buy[j] + p);
}
return sell[k];
}
}
func maxProfit(k int, prices []int) int {
if k >= len(prices)/2 { // effectively unlimited: take every rise
total := 0
for i := 1; i < len(prices); i++ {
total += max(0, prices[i]-prices[i-1])
}
return total
}
buy, sell := make([]int, k+1), make([]int, k+1) // after the j-th buy / j-th sell
for j := range buy {
buy[j] = math.MinInt / 2
}
for _, p := range prices {
for j := 1; j <= k; j++ {
buy[j] = max(buy[j], sell[j-1]-p)
sell[j] = max(sell[j], buy[j]+p)
}
}
return sell[k]
}