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

多状态动规水题

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    if(prices==null||prices.length<=1)return 0;
    const buy=[];
    const sell=[];
    buy[0]=-prices[0];
    buy[1]=Math.max(-prices[0],-prices[1]);
    sell[0]=0;
    sell[1]=Math.max(0,prices[1]-prices[0]);
    for(let i=2;i<prices.length;i++){
        buy[i]=Math.max(buy[i-1],sell[i-2]-prices[i]);//注意这里是 i - 2,不是 i-1 ,因为有冷冻期
        sell[i]=Math.max(sell[i-1],buy[i-1]+prices[i]);
    }
    return Math.max(buy[prices.length-1],sell[prices.length-1],0);
};

 

posted @ 2020-07-15 15:03  XXXSANS  阅读(154)  评论(0编辑  收藏  举报