用时8分20秒:
public int maxProfit(int[] prices) { int n = prices.length; if(n<=1) return 0; int min_price = prices[0]; int interest = 0; for(int i = 1;i<n;i++){ min_price = Math.min(min_price,prices[i]); interest = Math.max(interest,prices[i] - min_price); } return interest; }
做了如下修改,性能得到很大提升:
public int maxProfit(int[] prices) { int n = prices.length; if(n<=1) return 0; int min_price = prices[0]; int interest = 0; for(int i = 1;i<n;i++){ if(prices[i] < min_price) { min_price = prices[i]; }else{ interest = Math.max(interest,prices[i] - min_price); } } return interest; }
——2020.8.5