You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
思路
这道题不要过于在意冷静期哈,冷静期无非就是在写状态转移方程的时候,多加一个限制条件就行。
这道题可以用三个dp数组来求解。dp[ ][0]表示当天不持有股票并且没有出售股票,dp[ ][1]表示当天出售了股票所以不持有股票,dp[ ][2]表示当天持有股票。
第一种情况,前一天有可能出售了股票,也有可能没有股票也没卖过。
第二种情况,想要出售股票,前一天的状态必须是持有股票。
第三种情况,当天持有股票,可能是前一天本来既有的,也有可能是前一天买的股票。因为有冷静期的存在,因此,假如是前一天购买的股票,那么必然不是前一天购买的股票。
状态转移方程
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
dp[i][1] = dp[i-1][2] + prices[i]
dp[i][2] = max(dp[i-1][2], dp[i-1][0] - prices[i])
边界条件
dp[0][0] = 0;
dp[0][1] = 0;
dp[0][2] = -prices[0];
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int dp[30005][3];
dp[0][0] = 0; //不持有且没卖出去
dp[0][1] = 0; //不持有且卖出去了
dp[0][2] = -prices[0]; //持有
int len = prices.size();
for(int i = 1; i < len; i++)
{
dp[i][0] = max(dp[i-1][0], dp[i-1][1]);
dp[i][1] = dp[i-1][2] + prices[i];
dp[i][2] = max(dp[i-1][2], dp[i-1][0] - prices[i]);
}
return max(dp[len-1][0], dp[len-1][1]);
}
};