题目
给定一个整数数组,其中第 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])
- sold状态只能是当天从hold状态sell之后得到,
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)