一趟遍历。O(n)。期间记录最小的价格min的值并不断比较更新最大差价。
public class Solution { public int maxProfit(int[] prices) { // Start typing your Java solution below // DO NOT write main() function if (prices.length < 2) return 0; int min = prices[0]; int max = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < min) { min = prices[i]; } else { int val = prices[i] - min; if (val > max) max = val; } } return max; } }
第二刷:
class Solution { public: int maxProfit(vector<int> &prices) { int m = 0; if (prices.size() == 0) return m; int minPrice = prices[0]; for (int i = 0; i < prices.size(); i++) { if (prices[i] < minPrice) minPrice = prices[i]; int x = prices[i] - minPrice; if (x > m) m = x; } return m; } };