LeetCode 188. Best Time to Buy and Sell Stock IV (stock problem)
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).
分析
依然是stock problem模型,但这次必须压缩空间,否则超限,并且在 k>prices.size() 时,转化为k=+无穷的情况,否则超限。
const int inf=-999999;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(prices.size()<=1) return 0;
if (k >= prices.size()) {
int T_ik0 = 0, T_ik1 =inf;
for (auto price : prices) {
T_ik1 = max(T_ik1, T_ik0 - price);
T_ik0 = max(T_ik0, T_ik1 + price);
}
return T_ik0;
}
int sell[k+1]={0},buy[k+1];
fill(buy,buy+k+1,inf);
for(int i=0;i<prices.size();i++)
for(int j=1;j<=k;j++){
sell[j]=max(sell[j],buy[j]+prices[i]);
buy[j]=max(buy[j],sell[j-1]-prices[i]);
}
return sell[k];
}
};