https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
1. 思路
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking)利用状态机的思想来做,三个状态如下。
为什么这个方法能work呢,以题中例子为例:
每个状态都是当前能够拿到最多钱的状态,只有这样,为相应的下阶段服务时,下阶段才能达到拿最多钱的状态。
2. AC代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0) return 0;
int cool=0, buy=-1*prices[0], sell=INT_MIN, tmp;
for(int i=1; i<prices.size(); i++){
tmp = buy;
buy = max(buy, cool - prices[i]);
cool = max(cool, sell);
sell = tmp + prices[i];
}
return max(cool, max(sell, buy));
}
};