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列表为空时的判定

你可能感兴趣的:(LeetCode,LeetCode,python,121.,Best,Time,to,Buy,and,Sell,121.,买卖股票的最佳时机)