Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]output:5max. difference = 6-1 = 5 (Not 7-1 = 6, as selling-price needs-be-larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]output:0in this case, no transaction was done, i.e. Max Profit = 0.
Subscribe to see which companies asked this question
This problem is not seen in the beginning of dynamic planning ... It's good to see it. So pay attention to recognition.
Public classSolution { Public intMaxprofit (int[] prices) { if(Prices = =NULL|| Prices.length = = 0) { return0; } int[] res =New int[Prices.length]; intLow = Prices[0];res[0] = 0; for(inti = 1; i < prices.length; i++) { if(Prices[i] <Low ) { Low=Prices[i]; } Res[i]= Math.max (Res[i-1], prices[i]-Low ); } returnRes[prices.length-1]; }}
Of course, this code can also be optimized to optimize the space of O (1)
Public classSolution { Public intMaxprofit (int[] prices) { if(Prices = =NULL|| Prices.length = = 0) { return0; } intMax = 0; intLow = Prices[0]; for(inti = 1; i < prices.length; i++) { if(Prices[i] >Low ) {Max= Math.max (max, Prices[i]-Low ); } Else{ Low=Prices[i]; } } returnMax; }}
Notice the conditional judgment of the second method.
best time to Buy and Sell Stock Leetcode