zoukankan      html  css  js  c++  java
  • 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);
    };
  • 相关阅读:
    Windows CMD 配置 启动 服务
    Starting a Service
    socket 相关文章
    Qt GUI程序带命令行
    socket 双向
    winsock Options
    winsock 主动切断连接 Connection Setup and Teardown
    在 u 开头的单词前面,用 a 还是 an
    Web自动化----搭建基本环境
    Python----yield 生成器
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13305550.html
Copyright © 2011-2022 走看看