【LEETCODE】309-Best Time to Buy and Sell Stock with Cooldown

本文探讨了在股票市场中通过合理利用冷却期策略来实现最大利润的方法。详细介绍了如何设计算法以完成任意次数的买入和卖出操作,同时遵循特定的交易限制。通过分析实例和状态转移方程,读者将学会如何在不违反规则的情况下最大化自己的投资回报。

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:

prices = [1, 2, 3, 0, 2]

maxProfit = 3

transactions = [buy, sell, cooldown, buy, sell]


题意:

一个数组,第i个元素是某股票在第i天的价格,设计算法找到最大利润

可以进行多次买卖交易

限制条件是:在下次买入之前要先卖掉,并且卖掉后的第二天要cooldown不可以购买


参考:

http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/


引入辅助数组sellsbuys

sells[i]表示在第i天卖出股票所能获得的最大累积收益
buys[i]表示在第i天买入股票所能获得的最大累积收益

初始化令sells[0] = 0,buys[0] = -prices[0]

第i天交易时获得的累计收益只与第i-1天与第i-2天有关

记第i天与第i-1天的价格差:delta = price[i] - price[i - 1]

状态转移方程为:

sells[i] = max(buys[i - 1] + prices[i], sells[i - 1] + delta) 
buys[i] = max(sells[i - 2] - prices[i], buys[i - 1] - delta)

上述方程的含义为:

第i天卖出的最大累积收益 = max(第i-1天买入~第i天卖出的最大累积收益, 第i-1天卖出后反悔~改为第i天卖出的最大累积收益)
第i天买入的最大累积收益 = max(第i-2天卖出~第i天买入的最大累积收益, 第i-1天买入后反悔~改为第i天买入的最大累积收益)

而实际上:

第i-1天卖出后反悔,改为第i天卖出 等价于 第i-1天持有股票,第i天再卖出
第i-1天买入后反悔,改为第i天买入 等价于 第i-1天没有股票,第i天再买入

所求的最大收益为max(sells)。显然,卖出股票时才可能获得收益。


Python

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        size=len(prices)
        
        if not size:
            return 0
        
        buys=[None]*size
        sells=[None]*size
        
        sells[0]=0
        buys[0]=-prices[0]
        
        for x in range(1,size):
            delta=prices[x]-prices[x-1]
            
            sells[x]=max(buys[x-1]+prices[x],sells[x-1]+delta)
            buys[x]=max(buys[x-1]-delta,sells[x-2]-prices[x] if x>1 else None)
        
        return max(sells)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值