Personally, this is a relatively difficult DP problem. This link posts a typical DP solution to it. Need some time to get how it works.
The code is rewritten as follows.
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 intn = prices.size (), num =2;5 if(N <=1)return 0;6vector<vector<int> > dp (num +1, vector<int> (n,0));7 for(intK =1; K <= num; k++) {8 inttemp = dp[k-1][0]-prices[0];9 for(inti =1; I < n; i++) {TenDp[k][i] = max (Dp[k][i-1], Prices[i] +temp); Onetemp = max (temp, dp[k-1][i]-prices[i]); A } - } - returnDp[num][n-1]; the } -};
Personally, I prefer this solution, which are much easier to understand. The code is also rewritten as follows.
classSolution { Public: intMaxprofit (vector<int>&prices) { intstates[2][4] = {Int_min,0, Int_min,0}; intn = prices.size (), cur =0, next =1; for(inti =0; I < n; i++) {states[next][0] = max (states[cur][0], -Prices[i]); states[next][1] = max (states[cur][1], states[cur][0] +Prices[i]); states[next][2] = max (states[cur][2], states[cur][1] -Prices[i]); states[next][3] = max (states[cur][3], states[cur][2] +Prices[i]); Swap (cur, next); } returnMax (states[cur][1], states[cur][3]); }};
[Leetcode] best time to Buy and Sell Stock III