Is to find a state transition equation, the problem can be solved
But the state transition equation easy to find ah
Analysis Title:
Four states every day: buy, sell, freezing period, do nothing
The arrangement follows the daily status: buy ... buy ... sell ... sell cold cold ... ... which represents the day doing nothing, there may be multiple
Because some day doing nothing, no way to specify a certain day in the end was kind of operation, so the state as "the last operation of the day and before"
And the i-th day before the final operation is to buy the biggest gains obtained: sell [i]
Similarly defined buy [i], cool [i]
State transition equation:
sell[i]=buy[i-1]+price[i] buy[i]=max(cool[i-1]-prices[i],buy[i]) cool[i]=max(sell[i-1],cool[i-1])
Code:
class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); if (len == 0)return 0; vector<int> sell(len), buy(len), cool(len); sell[0] = 0; buy[0] = -1*prices[0]; cool[0] = 0; for (int i = 1;i < len;i++) { sell[i] = buy[i - 1] + prices[i]; buy[i] = max(cool[i - 1] - prices[i], buy[i - 1]); cool[i] = max(sell[i - 1], cool[i - 1]); } int ans = max(sell[len-1], buy[len-1]); years = max (age, cool [len - 1 ]); return years; } };