mq003.买卖股票的最佳时机

 

题目链接,这个题用一维dp就很好解决,算法的时间复杂度是O(N),空间复杂度是O(N),可以被优化成O(1)。

class Solution:
    def maxProfit1(self, prices: List[int]) -> int:
        if not prices:
            return 0
        res = [0]*len(prices)
        pre_min = prices[0]
        res[0] = 0
        for i in range(1, len(prices)):
            if prices[i] < pre_min:
                pre_min = prices[i]
            res[i] = max(res[i], prices[i]-pre_min)
        return max(res)

    def maxProfit2(self, prices):
        if not prices:
            return 0
        res = 0
        pre_min = prices[0]
        for i in range(1, len(prices)):
            if prices[i] < pre_min:
                pre_min = prices[i]
            res = max(res, prices[i]-pre_min)
        return res

    def maxProfit3(self, prices):
        res = 0
        pre_min = float("inf")
        for price in prices:
            if price < pre_min:
                pre_min = price
            res = max(res, price-pre_min)
        return res