题目描述
第一眼看到这道题,就想到了暴力破解,但是看这个范围,1 <= prices.length <= 10^5 ,两层 for 肯定超时
int profit = 0;
for (int buy = 0; buy < prices.length; buy++){
for (int sale = buy+1; sale < prices.length; sale++){
if (prices[buy] < prices[sale]){
int temp = prices[sale] - prices[buy];
profit = profit > temp ? profit : temp;
}
}
}
return profit;
你要卖股票哎,想让自己收益高,肯定要在最低点买进对吧,然后买了之后,再接下来的一段时间,看啥时候涨了,在最高点卖出
那就是想找 max ( prices[sale] - prices[buy] ) 想要最高收益,先在最低点买进,
即先找 min ( prices[buy] )
public class MaxProfit {
public static int getMaxProfit(int[] prices){
// 暴力破解
// int profit = 0;
// for (int buy = 0; buy < prices.length; buy++){
// for (int sale = buy+1; sale < prices.length; sale++){
// if (prices[buy] < prices[sale]){
// int temp = prices[sale] - prices[buy];
// profit = profit > temp ? profit : temp;
// }
//
// }
// }
// return profit;
//要找 max(prices[sale] - prices[buy]),即先找 min(prices[buy])
if (prices.length == 0 || prices == null){
return 0;
}
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 0; i < prices.length; i++){
if (prices[i] < minPrice){
minPrice = prices[i];
}else {
int temp = prices[i] - minPrice;
maxProfit = temp > maxProfit ? temp : maxProfit;
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = {1,2};
int maxProfit = getMaxProfit(prices);
System.out.println(maxProfit);
}
}