Given an array prices , It's the first i Elements prices[i] Represents the number of shares in a given stock i Sky price .
You can only choose One day Buy this stock , And choose A different day in the future Sell the stock . Design an algorithm to calculate the maximum profit you can get .
Return the maximum profit you can make from the deal . If you can't make any profit , return 0 .
Example 1:
Input :[7,1,5,3,6,4]
Output :5
explain : In the 2 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 6) Sell when , Maximum profit = 6-1 = 5 .
Note that profit cannot be 7-1 = 6, Because the selling price needs to be higher than the buying price ; meanwhile , You can't sell stocks before you buy them .
Example 2:
Input :prices = [7,6,4,3,1]
Output :0
explain : under these circumstances , No deal is done , So the biggest profit is 0.
The idea of this question is actually the comparison between the latter value and the previous value , Compare the compared value with the default value , If it is greater than , The default value is equal to the comparison value , The cycle goes on , But we have to deal with the boundary problem of the maximum value .
My answer :
public static int maxProfit(int[] prices) {
int min = prices[0];
int max = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i]<min){
min = prices[i];
}
if (i+1<prices.length) {
int i1 = prices[i + 1] - min;
if (max < i1) {
max = i1;
}
}
}
return max;
}