Best Time to Buy and Sell Stock IV - Hard - L - Star
Published:
Question
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Approach
- Variable iteration
- https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323
Solution
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if (n<2 || k<1) {
return 0;
}
if (k>n/2) {
int profit = 0;
for(int i=1; i<n; i++) {
profit += max(0, prices[i] - prices[i-1]);
}
return profit;
}
vector<int> buy(k, INT_MIN);
vector<int> sell(k, 0);
for(int i=0; i<n; i++) {
buy[0] = max(buy[0], -prices[i]);
sell[0] = max(sell[0], buy[0]+prices[i]);
for(int j=1; j<k; j++) {
buy[j] = max(buy[j], sell[j-1]-prices[i]);
sell[j] = max(sell[j], buy[j]+prices[i]);
}
}
return sell[k-1];
}
};