暴力循環
總是以最低的價格買入,以最高的價格賣出:
例如第一天買入,去找剩下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;}