best time to Buy and Sell Stock III
Problem:
Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You are in most of the transactions.
Ideas:
Dynamic planning
My Code:
Public classSolution { Public intMaxprofit (int[] prices) { if(Prices = =NULL|| Prices.length <= 1)return0; intSize =prices.length; int[] left =New int[size]; int[] right =New int[size]; intMin = prices[0]; intmax = Prices[size-1]; intRST = 0; for(intI=1; i<size; i++) {min=math.min (Min,prices[i]); Left[i]= Math.max (left[i-1],prices[i]-min); } for(intj=size-2; j>=0; j--) {Max=Math.max (Max,prices[j]); RIGHT[J]= Math.max (right[j+1],max-Prices[j]); } for(intk=0; k<size; k++) {rst= Math.max (rst, left[k]+Right[k]); } returnrst; }}View Code
The Learning Place:
- For the dynamic planning problem, but also more and more feel, but also know how to find the dynamic programming equation, is nothing more than reverse thinking, but there are two dynamic planning methods are not familiar, such as the topic of this progressive way left[i-1]<=left[i]<=left[i+1] The other way to solve the optimal solution is to find the optimal solution of all the local optimal solutions.
- For the problem that can not be thought out, should consider the following aspects, is there a rule? Can it be decomposed into several small problems, and then recursive solution or dynamic programming solution? Can you reduce the complexity of time by using the divide-and-conquer algorithm
- Get rid of bad habits, life, thinking, etc.
best time to Buy and Sell Stock III