188. Best Time to Buy and Sell Stock IV (Array; DP)

时间:2023-11-13 20:49:38

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:用状态存储至当前日为止第jth buy/sell的最大利润。到了第二天,我们可以按j从大到小(因为j大的新状态依赖于之前j小的状态),修改这个状态。

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int dates = prices.size();
if(dates <= || k == ) return ;
if (k >= prices.size()) return maxProfit2(prices); //unlimited transaction vector<int> release(k,); //sell stock
vector<int> hold(k,INT_MIN); //buy stock for(int i = ; i < dates; i++){
for(int j = k-; j > ; j--){
release[j] = max(release[j], hold[j]+prices[i]); //jth sell happen at ith day
hold[j]=max(hold[j], release[j-]-prices[i]); //jth buy happen at ith day
}
release[] = max(release[], hold[]+prices[i]);
hold[] = max(hold[],-prices[i]);
}
return release[k-];
} int maxProfit2(vector<int> &prices) {
int profit = ;
for (int i=; i<(int)prices.size()-; i++) {
if (prices[i+] > prices[i])
profit += prices[i+] - prices[i];
}
return profit;
}
};