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:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
解题思路
本题的操作逻辑如图:
每天可操作的事项分为三种:购入新股票、售出持有股票、冷却期
假如选择购入新股票,那么下一天的操作可以是等待或者售出当前股票;
假如选择冷却期,那么下一天可以继续不操作或者购入股票(前面售出)或者出售股票(前面购入);
假如选择售出股票,那么下一天的操作只能是进入冷却期。
那么,它们的收益如下:
buy 代表购入新股票,那么收益为max(之前的余额,购入新股票的余额);
sell 代表售出股票,那么收益为之前的余额加售出所得的总和;
nothing 代表前一天不进行操作,那么当前的收益为max(继续等待,售出股票);
C++代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0 || prices.size() == 1){
return 0;
}
int buy = -prices[0], sell = 0, nothing = 0;
int preBuy, preSell, preNothing;
for(int i = 1; i < prices.size(); i++) {
preBuy = buy;
preNothing = nothing;
preSell = sell;
buy = max(preBuy, preNothing-prices[i]);
nothing = max(preNothing, preSell);
sell = prices[i]+preBuy;
}
return max(sell, nothing);
}
};