源题目

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

309. 最佳买卖股票时机含冷冻期

难度中等865
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

  • 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
  • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

示例:
输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
通过次数107,786
提交次数178,607

分析题目:
每一天的四种状态:买进、卖出、冷冻期、什么都不做
每天的状态排列遵循:买…卖冷…买…卖冷… 其中…代表什么都不做的日子,可能有多个
因为有的日子什么都不做,没办法指明某一天到底进行了哪种操作,所以将状态定为“这一天及之前进行的最后操作”
第i天及以前,进行的最后操作为买进,所获得的最大收益:sell[i]
类似地定义buy[i] ,cool[i]
状态转移方程:
sell[i]=buy[i-1]+price[i]
buy[i]=max(cool[i-1]-prices[i],buy[i])
cool[i]=max(sell[i-1],cool[i-1])

  1. class Solution {
  2. /**
  3. * @param Integer[] $prices
  4. * @return Integer
  5. */
  6. function maxProfit($prices) {
  7. $len = count($prices);
  8. if(!$prices) return 0;
  9. $buy = [-$prices[0], 0];//考虑边界问题
  10. $sell = [0, 0];
  11. $cooldown = [0, 0];
  12. for($i = 1; $i < $len; $i ++){
  13. $sell[$i] = $buy[$i - 1] + $prices[$i];
  14. $buy[$i] = max($buy[$i - 1], $cooldown[$i -1] - $prices[$i]);
  15. $cooldown[$i] = max($cooldown[$i - 1], $sell[$i -1]);
  16. }
  17. $ans = max($sell[$len-1], $buy[$len-1]);
  18. $ans = max($ans, $cooldown[$len - 1]);
  19. return $ans;
  20. }
  21. }