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]