121. Best Time to Buy and Sell Stock
顺着数组走,保存:
1.到目前为止最大profit
2.到目前为止最小price
更新两个数据,结尾返回maxProfit
1 public int maxProfit(int[] prices) { 2 if(prices.length < 1) { 3 return 0; 4 } 5 int minPrice = prices[0]; 6 int maxProfit = 0; 7 for(int i = 1; i < prices.length; i++) { 8 minPrice = (prices[i] < minPrice)? prices[i]: minPrice; 9 maxProfit = (maxProfit < prices[i] - minPrice)? prices[i] - minPrice: maxProfit; 10 } 11 return maxProfit; 12 }