Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
程序员文章站
2022-06-17 18:33:47
...
这道题用的是dp的思想,用buy, sell, cooldown记录当前这些状态下最多的profit。
对于day i 而言:
sell[i] = buy[i-1] + prices[i]
buy[i] = max(muy[i-1], cooldown[i-1] - prices[i])
cooldown[i] = max(cooldown[i-1], sell[i-1])
空间优化:由于每次只需要知道上一次的情况,因此可以不使用数组,直接用变量记录sell, buy, cooldown
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 1:
return 0
#buy, sell, cooldown表示三种状态下最多的资金
#用第一天进行初始化
buy, sell, cooldown = -prices[0], 0, 0
for i in range(1, len(prices)):
last_sell = sell
sell = buy + prices[i]
buy = max(buy, cooldown - prices[i])
cooldown = max(cooldown, last_sell)
return max(sell, cooldown)
上一篇: leetcode----162. Find Peak Element
下一篇: java选择题
推荐阅读
-
LeetCode 121 Best Time to Buy and Sell Stock解析(股票买入卖出的最佳时间)
-
LeetCode_Array_123. Best Time to Buy and Sell Stock III买卖股票的最佳时机III(C++)
-
Leetcode No.121 Best Time to Buy and Sell Stock(c++实现)
-
309. Best Time to Buy and Sell Stock with Cooldown
-
Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
-
[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown
-
【DP + 卖股票】LeetCode 309. Best Time to Buy and Sell Stock with Cooldown
-
LeetCode题解系列--309. Best Time to Buy and Sell Stock with Cooldown
-
动态规划-309. Best Time to Buy and Sell Stock with Cooldown
-
(M)Dynamic Programming:309. Best Time to Buy and Sell Stock with Cooldown