暴力循环
总是以最低的价格买入,以最高的价格卖出:
例如第一天买入,去找剩下n-1天的最高价格,计算利润
依次计算到n-1天买入;
比较上述利润
// 运行时间超时。 o(n^2)
public int maxProfit1(int[] prices) {
int profit = 0;
for (int i = 0; i < prices.length-1; i++) {
int buy = prices[i];
for (int j = i+1; j < prices.length; j++) {
int sale = prices[j];
if(sale-buy > profit){
profit = sale-buy;
}
}
}
return profit;
}
最低点买入
只要保证在最低点买入,在合适的时间卖出,那么一定能获得最高利润
public int maxProfit2(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int profit = 0;
for (int i = 0; i < prices.length; i++) {
if(prices[i] < minPrice){
minPrice = prices[i];
} else if(prices[i] - minPrice > profit){
profit = prices[i] - minPrice;
}
}
return profit;
}