1. 程式人生 > 其它 >劍指 Offer 63. 股票的最大利潤(暴力,動態規劃)2

劍指 Offer 63. 股票的最大利潤(暴力,動態規劃)2

技術標籤:LeetCode

假設把某股票的價格按照時間先後順序儲存在陣列中,請問買賣該股票一次可能獲得的最大利潤是多少?

示例 1:

輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
注意利潤不能是 7-1 = 6, 因為賣出價格需要大於買入價格。
示例 2:

輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤為 0。

解法一:暴力,不推薦

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0, max = 0; //保證了利潤一定>0
        for(int i=0; i<prices.length; i++){
            for(int j=i+1; j<prices.length; j++){
                profit = prices[j] - prices[i];
                if(profit > max){
                    max = profit;
                }
            }
        }
        return max;
    }
}

解法二:動態規劃

複雜度分析:
時間複雜度O(N) : 其中 N為 prices列表長度,動態規劃需遍歷 prices。
空間複雜度 O(1) : 變數 cost和 profit使用常數大小的額外空間。

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

        return maxGap;
    }
}