121. Best Time to Buy and Sell Stock 购买股票的最佳时机

题目


代码部分一(227ms 22.38%)

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0; i < prices.length; i++){
            for(int j = i+1; j < prices.length; j++){
                max = Math.max(max, prices[j] - prices[i]);
            }
        }
        
        return max;
    }
}

代码部分二(3ms 58.59%)

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) return 0;
        
        int min = prices[0];
        int res = 0;
        for(int i = 1; i < prices.length; i++){
            if(min > prices[i])
                min = prices[i];
            res = Math.max(res, prices[i] - min);
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38959715/article/details/83721786