Leetcode-309. Best Time to Buy and Sell Stock with Cooldown 最佳买卖股票时机含冷冻期 (DP)

题目

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
链接:https://leetcode.com/problems/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:

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

思路及代码

DP
  • 对于每一天可能有三种状态,刚卖出(sold)、持有(hold)、什么都没有(rest)
    • sold状态只能是当天从hold状态sell之后得到,
      • 即sold[i] = hold[i-1] + prices[i]
    • hold状态可能是当天买进了股票,也可能是之前买进的,而当天什么也不做(不卖出)
      • 即hold[i] = max(hold[i-1], rest[i-1]-prices[i])
    • rest状态可能是前一天刚卖出股票(cooldown),或者休息不买进也不卖出
      • 即rest[i] = max(rest[i-1], sold[i-1])
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        hold = [float("-inf")]
        sold = [0]
        rest = [0]
        for i in range(n):
            hold.append(max(hold[i], rest[i]-prices[i]))
            sold.append(hold[i] + prices[i])
            rest.append(max(rest[i],sold[i]))
        return max(sold[n], rest[n])

复杂度

T = O ( n ) O(n) O(n)
S = O ( n ) O(n) O(n) -> O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值