算法: 冷却时间买卖股票的最佳时机309. Best Time to Buy and Sell Stock with Cooldown

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 冷却时间买卖股票的最佳时机309. Best Time to Buy and Sell Stock with Cooldown相关的知识,希望对你有一定的参考价值。

309. Best Time to Buy and Sell Stock with Cooldown

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

状态转移解法

关键是状态转换的 3 个状态和 5 个边。3 个状态是notHold (stock)、hold (stock)和notHold_cooldown。后两者的初始值为负无穷大,因为它们没有意义,即你一开始不会持有股票,一开始也没有冷却时间。5条边:

hold -----do nothing----->hold

hold -----sell----->notHold_cooldown

notHold -----do nothing -----> notHold

notHold -----buy-----> hold

notHold_cooldown -----do nothing----->notHold

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        notHold, notHoldCoolDown, hold = 0, float('-inf'), float('-inf')
        for p in prices:
            hold, notHold, notHoldCoolDown = max(hold, notHold - p), max(notHold, notHoldCoolDown), hold + p
        return max(notHold, notHoldCoolDown)

参考

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75942/4-line-Python-solution-52-ms

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/761981/PythonGo-O(n)-by-DP-and-state-machine.-w-Visualization

以上是关于算法: 冷却时间买卖股票的最佳时机309. Best Time to Buy and Sell Stock with Cooldown的主要内容,如果未能解决你的问题,请参考以下文章

309. 最佳买卖股票时机含冷冻期

力扣309.买卖股拍哦最佳时机含冷冻期

力扣309.买卖股拍哦最佳时机含冷冻期

309. 最佳买卖股票时机含冷冻期 DP

309. 最佳买卖股票时机含冷冻期

java 309.以冷却时间(dp).java买入和卖出股票的最佳时机