Daily LeetCode 309. Best Time to Buy and Sell Stock with Cooldown
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Medium
问题描述
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:
1 | Input: [1,2,3,0,2] |
思路及代码
这又是一道与股票相关的问题,与之前的买入卖出不同,这一题引入了cooldown
概念,每当执行一次卖出操作后,第二天必须cooldown
一天,不能够进行买入操作。在这样一个操作规则下,我们需要求出最大的利润。
我们可以用一个自动机来表示这个问题的三个状态:
三个状态的更新过程如下:
1 | #保持s0状态,或者从cooldown状态出来 |
代码如下:
1 | def maxProfit(prices): |
由于每一时刻状态只和前一个时刻有关,我们可以将空间复杂度减少到O(1):
1 | class Solution: |