309. Best Time to Buy and Sell Stock with Cooldown

该篇博客讨论了一个中等难度的算法问题,即在有冷却日限制的股票交易中如何实现最大利润。给定一个股票价格数组,你可以在任意一天买入和卖出,但卖出后第二天不能买入。解决方案涉及动态规划,通过维护两个数组buy和sell来记录在每个交易日结束时以买入和卖出结束的最大利润。博客提供了具体的代码实现,并给出了多个测试用例以验证算法的正确性。
摘要由CSDN通过智能技术生成

309. Best Time to Buy and Sell Stock with Cooldown

Medium

3803124Add to ListShare

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

 

Example 1:

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

Example 2:

Input: prices = [1]
Output: 0

 

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

转载:https://zhuanlan.zhihu.com/p/80078865

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        """
        转载:https://zhuanlan.zhihu.com/p/80078865
        
        assert Solution().maxProfit([1, 4, 100, 0, 10]) == 99
        assert Solution().maxProfit([1, 4, 100, 200]) == 199
        assert Solution().maxProfit([1, 4, 5, 0, 10]) == 13
        assert Solution().maxProfit([1, 2, 3, 0, 2]) == 3
        assert Solution().maxProfit([1, 4, 100, 100, 0, 10]) == 109
        assert Solution().maxProfit([1]) == 0
        
        解题思路:
        buy[i] = max(sell[i - 2] - price, buy(i - 1)),
        表示前i天的任意序列中以buy为结尾的最大利润,可以分别是前面i-1天中买的,也可以是在第i天买的(由于有cooldown,只能是sell[i-2])。
        sell[i] = max(buy(i - 1) + price, sell(i - 1)), 表示前i天的任意序列中以sell为结尾的最大利润。
        同理可以是当天卖出,也可以是前面卖出。全局最优肯定不能以持有结束,只会是sell[N-1]。
        时间复杂度:O(n),空间复杂度:O(n)
        """
        if prices is None:
            return 0
        n = len(prices)
        if n <= 1:
            return 0
        buy = [0] * n
        sell = [0] * n
        buy[0] = -prices[0]
        buy[1] = max(buy[0], -prices[1])
        sell[1] = max(0, prices[1] - prices[0])
        for i in range(2, n):
            buy[i] = max(sell[i - 2] - prices[i], buy[i - 1])
            sell[i] = max(buy[i - 1] + prices[i], sell[i - 1])
        return sell[n - 1]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值