121. 买卖股票的最佳时机

minPrice 维护到当天为止的最低价格

maxProfit 维护到当天我为止的最大利润

 

例如: [2,5,1,3],

第二天: minPrice=2 maxProfit=3;

第四天:minPrice=1 maxProfit=max(3, 3-1=2)=3;

复制代码
class Solution {
    public int maxProfit(int[] prices) {
        // 到当天为止的最小股票价格
        // minPrice 要初始化为最大值
        int minPrice = Integer.MAX_VALUE;
        // 到当天为止的最大利润
        int maxProfit = 0;

        for (int i=0;i<prices.length;i++) {
            minPrice = Math.min(minPrice, prices[i]);
            maxProfit = Math.max(maxProfit, prices[i] - minPrice);
        }
        return maxProfit;
    }
}
复制代码