309. Best Time to Buy and Sell Stock with Cooldown
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]
题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
思路
这题其实是看分享才学会的。分享里很详细的讲解了遇到股票问题该如何思考,附在文末,建议先看。
本题思路:在每一天上考虑所有可能的状态 的可能转移情形,然后记录最大的值。
对是否持有股票有2种状态:
1)持有
有两种转移情形:
1.1)昨天就持有;
1.2)昨天没有,今天入的。这里还要求前天也没有。
2)没持有
两种转移情形:
2.1)昨天有,今天卖的;
2.2)昨天就没有。
根据以上的思路建立记录数组(其实可以优化成单个)。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int num = prices.size();
if(num<=1) return 0;
int memo[num][2];
memo[0][0] = 0;
memo[0][1] = -prices[0];
memo[1][0] = max(memo[0][0], memo[0][1]+prices[1]);
memo[1][1] = max(memo[0][0]-prices[1], memo[0][1]);
for(int i=2; i<num; ++i){
memo[i][0] = max(memo[i-1][1]+prices[i], memo[i-1][0]);
memo[i][1] = max(memo[i-2][0]-prices[i], memo[i-1][1]);
}
return memo[num-1][0];
}
};
参考: