题目:
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]
思路:
这是一道典型的动态规划题目:我们定义三个数组:cooldown,buy以及sell,分别表示第i天的状态为cool down,buy或者sell。则其状态转移方程为:
1)如果第i - 1天是cool down状态,那么第i天既可以继续保持cool down状态,也可以买入一只股票从而进入buy状态;
2)如果第i - 1天是buy状态,那么第i天既可以继续保持buy状态,也可以卖掉手中所拥有的这只股票,从而进入sell状态;
3)如果第i - 1天是sell状态,那么第i天就不然是cool down状态。
因此可以如下面代码和注释所示,写出相应的递推公式。
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int days = prices.size();
if(days <= 1) {
return 0;
}
vector<int> cooldown(days, 0); // cool down in the i-th day
vector<int> buy(days, 0); // buy a new stock in the i-th day
vector<int> sell(days, 0); // sell the stock in the i-th day
// base
cooldown[0] = 0;
buy[0] = -prices[0];
sell[0] = 0;
// deduction
for(int i = 1; i < days; ++i) {
cooldown[i] = max(cooldown[i - 1], sell[i - 1]); // stay at cooldown, or rest from sell
buy[i] = max(buy[i - 1], cooldown[i - 1] - prices[i]); // stay at buy, or buy from cooldown
sell[i] = buy[i - 1] + prices[i]; // sell from buy
}
return max(cooldown[days - 1], sell[days - 1]);
}
};