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.
Ideas
I know that if you want to get a profit, the price sold must be higher than the buy price, and the date of sale is greater than the date of the purchase. So we buy at the lowest time and sell at the highest time. From day one, the first day of the price is set to the current lowest price, if the price of the next day is higher than the lowest price, we record the price difference at this time, if the profit is greater than the previous maximum profit then set it to the current maximum profit, and then the subscript moves backwards. If one day the price is lower than the current minimum price, we set the current price to the lowest price, and then continue the process until the end of the array is traversed. This process actually divides the array into a section, and the beginning of each paragraph is the lowest value within the range. For example: [2,24,4,1,3,7] The red section of 2 is the minimum value, and 24 is the maximum value. The Green section 1 is the minimum value, and 7 is the maximum value.
The code is as follows:
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 intMin = 0;4 intMP = 0;5 6 for(inti = 1; i < prices.length; i++) {7 if(Prices[min] > prices[i]) min =i;8 ElseMP = Math.max (MP, Prices[i)-prices[min]);9 }Ten One returnMP; A } -}
Leetcode OJ 121. best time to Buy and Sell Stock