Best Time to Buy and Sell Stock with Cooldown_LeetCode

本文介绍了一种基于动态规划的算法,用于计算给定股票价格序列下,遵循特定交易规则时的最大利润。通过定义四种状态(Sell, Hold, Buy, CD),并利用递推公式,实现了对任意交易天数的最优策略求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#Say you have an array for which the ith element is the price of a given stock on day i.
#Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

    #You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
    #After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

#Example:

#Input: [1,2,3,0,2]
#Output: 3
#Explanation: transactions = [buy, sell, cooldown, buy, sell]

#主要思路:动态规划,从最后一步开始倒推:
#情况无非四种:
#1,Sell:持有一个股并卖出——上一步必然是2 or 3
#2,Hold:持有一个股并继续持有——上一步必然时2 or 3
#3,Buy:没有股票,买入——上一步必然是4
#4,CD:没有股票,不操作——上一步必然是1 or 4
#以i代表i时刻,Sell[i]意为"在i时刻执行Sell操作时的最大利润"
#写出四种行为的表达式:
#Sell[i] = max(Buy[i-1]+price, hold[i-1]+price)
#Hold[i] = max(Buy[i-1], hold[i-1])
#Buy[i] = CD[i-1]-price
#CD[i] = max(Sell[i-1], CD[i-1])
#“Now you want to maximize your total profit,
#but you don't know what action to take on day i such that you get the total maximum profit,
#so you try all 4 actions on every day.
#Suppose you take action 1 on day i, since there are two possible actions on day i-1, namely actions 2 and 3,
#you would definitely choose the one that makes your profit on day i more. Same thing for actions 2 and 4.
#So we now have an iterative algorithm.”——ElementNotFoundException
#另外初始的值设定很重要: At Stage 0 : sell, hold, buy, cd = 0, -prices[0], -prices[0], 0

#动态分布,从结果开始以最佳策略进行倒推论
class Solution(object):
    def maxProfit(self, prices):
        if not prices:
            return 0
        sell, hold, buy, cd = 0, -prices[0], -prices[0], 0
        for price in prices:
            sell, hold, buy ,cd = max(buy+price, hold+price), max(buy, hold), cd - price, max(sell,cd)
        return max(sell,hold,buy,cd)

转载于:https://www.cnblogs.com/phinza/p/10271275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值