【Leetcode每日笔记】309. 最佳买卖股票时机含冷冻期(Python)

题目

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

示例:

输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

解题思路

动态规划

状态定义

buy[i]表示第i天持股的最大利润,sell[i]表示第i天不持股的最大利润

状态转移方程

需要跳过冷冻期,那么第i天持股,需要考虑的是前两天不持股的情况;
前两天的定义:
buy[0] ,buy[1]= -prices[0],max(-prices[1],-prices[0])
sell[0],sell[1] = 0,max(prices[1]-prices[0],0)
后面的方程
buy[i] = max(buy[i-1],sell[i-2]-prices[i])
sell[i] = max(sell[i-1],buy[i-1]+prices[i])

代码

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices or prices == sorted(prices,reverse=True):
            return 0
        buy = [0 for _ in range(len(prices))]
        sell = [0 for _ in range(len(prices))]
        buy[0] ,buy[1]= -prices[0],max(-prices[1],-prices[0])
        sell[0],sell[1] = 0,max(prices[1]-prices[0],0)
        for i in range(2,len(prices)):
            buy[i] = max(buy[i-1],sell[i-2]-prices[i])
            sell[i] = max(sell[i-1],buy[i-1]+prices[i])
        return max(sell)

#【Leetcode每日笔记】714.买卖股票的最佳时机(Python)

猜你喜欢

转载自blog.csdn.net/qq_36477513/article/details/111862420
今日推荐