First, the topic
1, examining
2. Analysis
Give an array so that you have val1 to buy, and then sell with Val2, to get the most profit.
Second, the answer
1, Ideas:
Method One,
The minimum value that is recorded to the current position with the Traverse min;
Max records the maximum profit that is obtained when the price of the current array value is sold.
Public intMaxprofit (int[] prices) { if(Prices.length < 2) return0; intMin = prices[0]; intMax = 0; for(inti = 1; i < prices.length; i++) { if(Prices[i]-min > 0 && prices[i]-min >max) {Max= Prices[i]-min; } Else if(Prices[i] <min) min=Prices[i]; } returnMax; }
Optimization:
The variable minprice directly records the current minimum value.
Public int maxProfit3 (int[] prices) { int minprice = integer.max_value, MAX = 0; c8/> for (int i = 1; i < prices.length; i++) { = math.min (minprice, Price S[i]); = Math.max (max, prices[i]- minprice); } return max; }
Method Two,
Adopt "Kadane ' s algorithm.", that is, the idea of using the maximal and the continuous substring.
Curmax: The profit earned at the current price (if you don't make money, you don't sell).
①, if Curmax = 0, means that the current value is smaller than the value of the front;
②, Curmax > 0, i.e., Curmax = (price[i-1]-price[i-2] + price[i]-price[i-1]) = Price[i]-price[i-1]. That is, the current price is the maximum value, and the lowest value is subtracted from the front.
Max: The maximum profit in the total process.
Public int maxProfit2 (int[] prices) { int curmax = 0, max = 0; for (int i = 1; i < prices.length; i++) { = Math.max (0, Curmax + = prices[i]-prices[i-1]); = Math.max (Curmax, max); } return max; }
121. Best time to Buy and Sell Stock