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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]
dp思路是这样的:
第i天进行买入操作,则应该选择[0,i-2]天sell完成的结果上进行,而且是取区间内的最大值;
第i天进行卖出操作,则应该选择[0,i-1]天buy完成的结果上进行,而且是区间最大值;
所以保存四个数组:
buy;
sell;
max_after_buy;
max_after_sell;
c++实现:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size()<=1)
return 0;
const int len=prices.size();
int buy[len];
int sell[len];
int max_after_buy[len];
int max_after_sell[len];
buy[0]=-prices[0];
buy[1]=-prices[1];
sell[0]=0;
sell[1]=max(0,prices[1]-prices[0]);
max_after_buy[0]=-prices[0];
max_after_buy[1]=max(-prices[0],-prices[1]);
max_after_sell[0]=sell[0];
max_after_sell[1]=max(sell[0],sell[1]);
for (int i=2;i<len;i++){
buy[i]=max_after_sell[i-2]-prices[i];
sell[i]=max_after_buy[i-1]+prices[i];
max_after_buy[i]=max(max_after_buy[i-1],buy[i]);
max_after_sell[i]=max(max_after_sell[i-1],sell[i]);
}
// for (int i=0;i<len;i++)
// cout<<buy[i]<<" ";
// cout<<endl;
// for (int i=0;i<len;i++)
// cout<<sell[i]<<" ";
// cout<<endl;
// for (int i=0;i<len;i++)
// cout<<max_after_sell[i]<<" ";
// cout<<endl;
// for (int i=0;i<len;i++)
// cout<<max_after_buy[i]<<" ";
// cout<<endl;
return max_after_sell[len-1];
}
};