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]
s思路:
1. 和 Leetcode 122. Best Time to Buy and Sell Stock II比,多了一天cooldown. 那代码如何建模或者模拟这个cooldown?
2. 难点是,cooldown是哪一天重要吗?需要尝试完所有的情况,然后找出最大值吗?这么看,这个角度很繁琐,可以主动换一个角度看问题吗?还是dp,回到数学递推公式来!
3. 忘了这个题应该是dp的题了,现在增加了一个cooldown,就不能用原来简化的dp来做了,参考了https://discuss.leetcode.com/topic/30421/share-my-thinking-process
4. 假设buy[i]表示第i天之前包括第i天最后的操作是买入对应的最大profit;sell[i]表示第i天之前包括第i天最后的操作是卖出对应的最大profit。由于有一天cooldown,所以这两个数量的interplay就是如下:
buy[i]=max(sell[i-2]-price,buy[i-1]);//sell[i-2]表示i-2卖出,中间一天cooldown, 然后买入的价格为price. 还有一种可能是第i天不操作的收益最大,也就是等于buy[i-1].
sell[i]=max(buy[i-1]+price,sell[i-1]);//i-1天买入后的最大收益加上今天卖出后得到的收益,还有一种可能是第i天不卖出,收益最大,即:还等于sell[i-1].
5. 再次看出数学的牛!但是能用数学,前提是想明白了,而且认可这个数学,相信是数学关系,而不是模仿一下,这样下次还是搞不定!
6. 分析一下为什么数学可以表示cooldown呢?另外,分析一下此类问题,就是递推关系是几个状态之间相互转移的,有点像马尔科夫链一样,而什么问题可以模拟成状态转换呢?明天再写!
//方法1:dp,数学表示递推关系!
class Solution {
public:
int maxProfit(vector<int>& prices) {
//
int buy=INT_MIN;
int sell[3]={0};
for(int p:prices){
int pre_buy=buy;
buy=max(sell[0]-p,pre_buy);
sell[2]=max(pre_buy+p,sell[1]);
sell[0]=sell[1];
sell[1]=sell[2];
}
return sell[2];
}
};