Difficulty: Medium
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]
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size= prices.size();
if(size<2) return 0;
vector<int> sell(size, 0), buy(size, 0), cooldown(size, 0);
buy[0]=-prices[0];
for(int i=1; i<size; i++){
sell[i]=max(buy[i-1]+prices[i], cooldown[i-1]);
buy[i]=max(cooldown[i-1]-prices[i], buy[i-1]);
cooldown[i]=max(sell[i-1], cooldown[i-1]);
}
return max(sell[size-1], cooldown[size-1]);
}
};
DP:
sell[n]=max{buy[n-1]+prices[n], cooldown[n-1]};
buy[n]=max{cooldown[n-1]-prices[n], buy[n-1]};
cooldown[n]=max{sell[n-1], cooldown[n-1]};
sell[n]时,为第n日操作为sell时的最大利润,buy[n],cooldown[n]同理。
注意在buy操作后未卖出,状态仍为buy而不为cooldown。