题目
给定一个整数数组,其中第
i
个元素代表了第i
天的股票价格 。设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
1
2
3 输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
动态规划
也就是说,对于可以多次买卖股票的问题,我们如何穷举所有情况?
具体到每一天,对所有状态进行暴力枚举。本问题中,每一天的状态可以用:
- 今天是第几天?
- 是否持有股票?
- 买入、卖出还是无操作?
来表示,有了这三个状态,就可以计算每一种状态的利润:
- 如果我当天持有股票(不空仓),那么前一天只能是买入或者无操作,而当天只能平仓或无操作;
- 如果当天空仓,那么前一天有可能非空仓且进行平仓,或者是空仓且无操作;
- 如果前一天非空仓且进行了平仓,那么当天冻结,只能无操作;
- 如果前一天是空仓且无操作,那么当天可以买入或无操作;
1 | // date: d |
代码:
1 | class Solution { |
- 时间复杂度$O(N)$
- 空间复杂度$O(N)$,可优化为$O(1)$
总结
这种暴力列举状态的方法可以一种思路破解六道股票问题,其核心思路就是暴力枚举所有状态,列出状态转移方程,然后再对空间进行优化。