代码随想录训练营第III期--049--python

# 代码随想录训练营第III期--049--python

# 抄的,没过脑子

#  121. 买卖股票的最佳时机 
class Solution:
    def maxProfit(self, prices):
        length = len(prices)
        if length == 0: return 0
        dp = [[0] * 2 for _ in range(length)]
        dp[0][0] = -prices[0]
        dp[0][1] = 0 
        for i in range(1, length):
            dp[i][0] = max(dp[i-1][0], -prices[i])
            dp[i][1] = max(dp[i-1][1], prices[i] + dp[i-1][0])
        return dp[-1][1]

#  122.买卖股票的最佳时机II
 class Solution:
    def maxProfit(self, prices):
        length = len(prices)
        dp = [[0] * 2 for _ in range(2)]
        dp[0][0] = -prices[0]
        dp[0][1] = 0 
        for i in range(1, length):
            dp[i%2][0] = max(dp[(i-1) %2][0], dp[(i-1) % 2][1] - prices[i])
            dp[i%2][1] = max(dp[(i-1) % 2][1], dp[(i-1) % 2][0] + prices[i])
        return dp[(length - 1) % 2][1]


        

你可能感兴趣的:(代码随想录,python,算法,leetcode)