1. Best time to Buy and Sell Stock II
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 if(Prices.size () <1)//prices.size is unsigned int5 return 0;6 intPro =0;7 for(intI=0; I<prices.size ()-1; i++)8 {9 if(prices[i+1] >Prices[i])TenPro + = prices[i+1]-Prices[i]; One } A returnPro; - } -};
The actual stock is impossible to know after today's fares, otherwise it will be based on the trend, every time to take the valley and the peak can be.
2. Best time to Buy and Sell Stock with Cooldown
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 intn =prices.size ();5 if(N <2) 6 return 0;7vector<int> Sells (n,0);8vector<int> Buys (N,0);9 intDelay =0;Tensells[0] =0; Onebuys[0] =-prices[0]; Asells[1] = prices[1]-prices[0]; -buys[1] =-prices[1]; - intres = MAX (0, prices[1]-prices[0]); the for(intI=2; i<n; ++i) - { -Delay = prices[i]-prices[i-1]; -Buys[i] = max (sells[i-2]-prices[i], buys[i-1]-delay); +Sells[i] = max (buys[i-1]+prices[i], sells[i-1]+delay); - if(Res <Sells[i]) +res =Sells[i]; A } at returnRes; - } -};
Analysis See: http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/
3.
best time to Buy and Sell stock Series