这里都用了状态机,需要注意的是状态机表示当前状态下的最大收益
a typical DP problem
key1 : deduce the transition function .
(buy,sell,rest) represents before day i what is the max profit when the sequence end with (buy, sell ,rest)
buy[i] = max(rest[i-1]-price[i],buy[i-1])
sell[i] = max(buy[i-1] + price[i],sell[i-1])
rest[i] = max(buy[i-1],sell[i-1],rest[i-1])
key2: simplifize the function
buy[i] = max(sell[i-2]-price[i],buy[i-1])
sell[i] = max(buy[i-1] + price[i],sell[i-1])
key3: initialize i = 0
buy[0] = max(INT_MIN, -price[0])
sell[0] = 0;
here is the code
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 0) return 0;
vector<int> buy(len);
vector<int> sell(len);
buy[0] = -prices[0];
sell[0] = 0;
for(int i = 1; i < len ; i++){
if(i == 1){
buy[1] = max(-prices[1],buy[0]);
}else{
buy[i] = max(sell[i-2]-prices[i],buy[i-1]);
}
sell[i] = max(buy[i-1]+prices[i],sell[i-1]);
}
return sell[len-1];
}
714. Best Time to Buy and Sell Stock with Transaction Fee
一样的dp思想,需要注意的是一次买入再卖出才算一次transaction
int maxProfit(vector<int>& prices, int fee) {
int len = prices.size();
if(len == 0) return 0;
vector<int> sell(len);
vector<int> buy(len);
buy[0] = -prices[0];
sell[0] = 0;
for(int i = 1; i < len ;i++){
buy[i] = max(buy[i-1], sell[i-1]-prices[i]); //买入的时候不需要付费
sell[i] = max(sell[i-1], buy[i-1]+prices[i] -fee);
}
return sell[len-1];
}
123. Best Time to Buy and Sell Stock III
int maxProfit(vector<int>& prices, int fee) {
if(prices.size() == 0) return 0;
int s1 = -prices[0], s2 = INT_MIN, s3 = INT_MIN,s4 = INT_MIN;
for(int i = 0; i < prices.size(); i++){
s1 = max(s1, -prices[i]);
s2 = max(s2, s1+prices[i]);
s3 = max(s3, s2-prices[i]);
s4 = max(s4, s3+prices[i]);
}
return max(0,s4);
}
122. Best Time to Buy and Sell Stock II
int maxProfit(vector<int>& prices, int fee) {
int len = prices.size();
if(len == 0) return 0;
vector<int> sell(len);
vector<int> buy(len);
buy[0] = -prices[0];
sell[0] = 0;
for(int i = 1; i < len ;i++){
buy[i] = max(buy[i-1], sell[i-1]-prices[i]);
sell[i] = max(sell[i-1], buy[i-1]+prices[i]);
}
return sell[len-1];
}