1.
ref:http://blog.csdn.net/linhuanmars/article/details/23164149
The difference is that it can be traded infinitely many times (of course we know that the deal will not exceed n-1 times, that is, every day we sell first and buy it). Since there is no limit to the number of transactions, we can see that we can get the maximum profit if we trade for a two-day spread greater than 0. So the algorithm is actually adding up all the spreads greater than 0 can be, very simple. So only a single scan is required, the time complexity is O (n), space only need O (1) to save a cumulative result can be.
1 Public intMaxprofit (int[] prices) {2 if(Prices.length < 1) {3 return0;4 }5 intdiff = 0;6 for(inti = 1; i < prices.length; i++) {7diff + = (prices[i]-prices[i-1] > 0)? Prices[i]-prices[i-1]: 0;8 }9 returndiff;Ten}
2. Motion Regulation
Maintain two variables:
1. End of day, no stock on hand
1) No stock in the past, nothing to do today
2) There were stocks, bought today
2. The end of the day, there is stock in hand
1) No previous stock, buy today
2) There were stocks, and nothing was done today.
1 Public intMaxprofit (int[] prices) {2 if(Prices.length < 1) {3 return0;4 }5 intNostock = 0;6 intHavestock = 0-prices[0];7 for(inti = 1; i < prices.length; i++) {8 intOldnostock =Nostock;9Nostock = Math.max (nostock, Havestock +prices[i]);TenHavestock = Math.max (Havestock, Nostock-prices[i]); One } A returnNostock; -}
122. Best time to Buy and Sell Stock II