1. 程式人生 > >LeetCode(Python版)——121. Best Time to Buy and Sell Stock

LeetCode(Python版)——121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.

分治法:將陣列分成左右兩部分,最大利潤有3種情況,第一種在左側,第二種在右側,第三種是橫跨左右兩部分,即最小買入在左側,最大賣出在右側。計算三種情況的最大利潤,輸出最大的結果。時間複雜度為O(nlogn)

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        length = len(prices)
        if length == 0:
            return 0
        return self.divide(prices, 0, length - 1)
    
    def divide(self, prices, s, t):
        if s == t:
            return 0
        
        mid = (s + t) // 2
        
        lmin = prices[s]
        for i in range(s, mid + 1):
            if prices[i] < lmin:
                lmin = prices[i]
        
        rmax = prices[mid + 1]
        for i in range(mid + 1, t + 1):
            if prices[i] > rmax:
                rmax = prices[i]
        
        maxProfit = rmax - lmin
        
        lmaxProfit = self.divide(prices, s, mid)
        rmaxProfit = self.divide(prices, mid + 1, t)
        if lmaxProfit > maxProfit:
            maxProfit = lmaxProfit
        if rmaxProfit > maxProfit:
            maxProfit = rmaxProfit
        return maxProfit

動態規劃:d[i] 表示前i + 1個價格中最大利潤, min[i] 表示前i + 1箇中最小的買入價格,d[i + 1] = max{d[i], prices[i + 1] - min[i]},求出d[i + 1]後,更新min[i + 1],時間複雜度為O(n)

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        length = len(prices)
        if length == 0:return 0
        d = [0] * length
        min = [0] * length
        d[0] = 0
        min[0] = prices[0]
        
        for i in range(1, length):
            d[i] = prices[i] - min[i - 1]
            min[i] = prices[i]
            if d[i] < d[i - 1]:
                d[i] = d[i - 1]
            if min[i - 1] < min[i]:
                min[i] = min[i - 1]
        
        return d[length - 1]

注意:要考慮prices列表為空時的判定