Best Time to Buy and Sell Stock
只能买1次的股票问题
思路:遍历数组的同时,记录到当前天为止的历史最低价格,那么在当前天卖出的最大收益就是当前价格减去历史最低价格,同时更新历史最大收益。
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if (prices == null || prices.length == 0) { 4 return 0; 5 } 6 int min_price = Integer.MAX_VALUE; 7 int max_profile = 0; 8 9 for (int i : prices) { 10 min_price = Math.min(min_price, i); 11 max_profile = Math.max(max_profile, i - min_price); 12 } 13 14 return max_profile; 15 } 16 }