刷題309. Best Time to Buy and Sell Stock with Cooldown

一、題目說明

題目309. Best Time to Buy and Sell Stock with Cooldown,計算買賣股票的最大利潤,賣出股票後第二天不能買入,需要冷卻一天。

二、我的解答

這個題目,我沒做出來。看了高手的解答,才知道用dp。

class Solution{
	public:
		//sold[i] = hold[i-1] + price[i];
		//hold[i] = max(hold[i-1], rest[i-1] - price[i])
		//rest[i] = max(rest[i-1], sold[i-1])
		//最後一天max(sold,rest)
		int maxProfit(vector<int>& prices){
			int sold=0,rest=0,hold=INT_MIN;
			for(int p: prices){
				int pre_sold = sold;// sold[i-1]
				sold = hold + p; //sold[i]
				hold = max(hold,rest-p); // hold[i]
				rest = max(rest,pre_sold);
			}
			return max(sold,rest);
		}
};

性能如下:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock with Cooldown.
Memory Usage: 8.7 MB, less than 55.56% of C++ online submissions for Best Time to Buy and Sell Stock with Cooldown.

三、優化措施

dp狀態方程怎麼來?

每一天有3個狀態:

持有hold:可以是前一天買入的繼續持有;或者前一天冷卻今天買入,取其最大值。

max(hold[i-1], rest[i-1] - price[i])

賣出sold: 賣出是前一天持有量 + 賣出的價格

sold[i] = hold[i-1] + price[i]

冷卻rest:前一天冷卻今天繼續冷卻,或者前一天賣出今天冷卻,取其最大值。

rest[i] = max(rest[i-1], sold[i-1])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章