1. 程式人生 > >121. Best Time to Buy and Sell Stock 購買股票的最佳時機

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;
    }
}