题目描述:
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]
题目大意:
- 其实这道题是属于LeetCode股票买卖问题中的一道,是第二道题的进阶版本
- 上第二道题,LeetCode算法题之122. Best Time to Buy and Sell Stock II(easy)【Python3题解】
- 看过链接的就知道,在链接的题目前面其实还有一道题,都是进阶版本,一步一步增加难度
- 在本题中,多了冷冻期的概念,大意是在你买了股票之后的一天里,你不能进行买股票,而过了那一天你才能买卖
解题思路:
- 其实在买卖股票问题II中,多定义了一个变量,用来记录昨天的收益值,因为你买卖股票的次数是没有限制的,所以你的收益值是可以累加的
- 而在本题中,到底是什么变了呢?
- 有一个规律性的东西在里面,就是[buy, sell, cooldown],这是循环出现的,当然可能不是循环结束后,一定停留在cool down的状态
- 那多了这个限定条件以后,哪里发生变化了呢?
- 就是在你的收益上,在没有冷冻期的题目中,你的收益记录前一天的就可以,也就是昨天,因为只有你卖了股票之后,才会有收益啊,记录下来,当你再次买的时候,就拿你的收益值去减去当天的股票价格了,这样循环下来,就是交易次数无限次了
- 那现在有了冷冻期,你卖了之后,有一天不能交易,当你想再次交易的时候,其实你用的收益值是你前天的收益值
- 所以,在新定义一个变量,把前天的收益值也记录下来,当你买股票的时候,用它去减价格,就可以提交正确
少废话,上代码:
class Solution:
def maxProfit(self, prices):
dp_i_0 = 0
dp_i_1 = float("-inf")
# 新定义一个变量,代表前一天你的收益值大小,
# 因为有了冷冻期,你再次买股票的时候,花的钱,是需要在你前一天的收益中减去
dp_pre_profit = 0
for i in range(len(prices)):
temp_profit = dp_i_0
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = max(dp_i_1, dp_pre_profit - prices[i])
dp_pre_profit = temp_profit
return dp_i_0
运行时间和内存占用:
- Runtime: 24 ms, faster than 99.88% of Python3 online submissions for Best Time to Buy and Sell Stock with Cooldown.
- Memory Usage: 13.8 MB, less than 13.64% of Python3 online submissions for Best Time to Buy and Sell Stock with Cooldown.