Topic
the best time to buy and sell stocks
Suppose there is an array, the first element of which is the price of a given stock in the first day. If you are allowed to complete only one transaction at most (for example, buying and selling a stock), design an algorithm to find out the maximum profit.
Sample Example
give an example of an array [3,2,3,1,2], return 1
Solving
The popular point is to ask for the following number minus the maximum value of the preceding number, and the last and 0 to take the maximum value.
Direct violence, time of the Impurity O (N2)
Public classSolution {/** * @paramprices:given an integer array *@return: Maximum Profit*/ Public intMaxprofit (int[] prices) { //Write your code here intMax = 0; if(Prices = =NULL|| Prices.length = = 0) return0; for(inti = 0;i< prices.length; i++){ for(intj = i;j< Prices.length; j + +) Max= Math.max (max, Prices[j]-Prices[i]); } returnMax; }}Java Code
The above program is also a j==i, do not compare the final result and 0 to take the maximum value.
So the question is, is there a better way?
Divided into two parts, the first half of the minimum value of the second half of the maximum value, the subtraction is the answer, this seemingly difficult solution.
At the time of the variable array, the minimum value in front of it is compared, and the current node can be regarded as the maximum value, the difference between the assumed maximum value and the minimum value of the previous one, and the profit obtained from the current node's sell, is the local maximum value.
The maximum value of the local maximum is the overall maximum value.
Public classSolution {/** * @paramprices:given an integer array *@return: Maximum Profit*/ Public intMaxprofit (int[] prices) { //Write your code here intresult = 0; if(Prices = =NULL|| Prices.length = = 0) return0; intMin = prices[0]; for(inti = 1;i< prices.length; i++) {result= Math.max (Result,prices[i]-min); Min=math.min (Min,prices[i]); } returnresult; }}Java Code
Total time: 1303 Ms
classSolution:"""@param prices:given An integer array @return: Maximum profit""" defMaxprofit (Self, prices):#Write your code here ifPrices = = NoneorLen (prices) = =0:return0 Min=Prices[0] Res=0 forPinchPrices:res= Max (res,p-Min) Min=min (min,p)returnRes
Python Code
Total time: 218 ms
Lintcode Medium Title: