第16天
2020.07.10 周四
难度系数:中等
题目:309最佳买卖股票时机含冷冻期
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
——————————我是分割线——————————
解法:
思路:动态规划
sell——最后卖时的最大利润,初始化0
buy——最后买时的最大利润,初始化-prices[0]
freeze——最后冷冻时的最大利润,初始化0
从下标1开始遍历prices
sell = max(sell, buy+prices[i])
卖完冷冻;买完卖
buy = max(buy, freeze-prices[i])
买完卖;冻完买
freeze = sell
代码:
(这里放的是我本地编译器测试的代码)
#leetcode309最佳买卖股票时机含冷冻期 2020.07.10
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
sell = 0
buy = -prices[0]
freeze = 0
for i in range(1, len(prices)):
sell, buy, freeze = max(sell, buy+prices[i]), max(buy, freeze-prices[i]), sell
# print("sell:",end = '')
# print(sell,end = '')
# print(" buy:",end = '')
# print(buy,end = '')
# print(" freeze:",end = '')
# print(freeze)
return sell
prices = [1,2,3,0,2]
# prices = [1]
print(Solution().maxProfit(prices))
# 结果3