记录最大的差值即可。
如果当前值-买入的值小于0,说明还有最低价可以买入,故而可以选择此时的值作为新的买入值。
否则就计算差值大小,计算差值保留最大即可。
public int maxProfit (int[] prices) { // write code here int max_profit = 0; int mr = 0; for(int i=0;i<prices.length;i++){ if(prices[i] - prices[mr] < 0){ mr = i; }else{ max_profit = Math.max(max_profit, prices[i] - prices[mr]); } } return max_profit; }