zoukankan      html  css  js  c++  java
  • 买卖股票专题系列5---最佳买卖股票时机含冷冻期

    题目: 

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

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

    题解:

      此题是典型的动态规划解法。动态规划2步走:

      1.状态定义

        对于股票我们分为持有、不持有2种状态:   

       memo[i][0]表示第i天不持有股票的最大利润
    
       memo[i][1]表示第i天持有股票的最大的利润

      2.状态转移方程    

      //第i天不持有股票的最大利润 = Math.max(昨天就不持有,昨天持有且今天卖出)
      memo[i][0] = Math.max(memo[i-1][0],memo[i-1][1]+prices[i]);


      //第i天持有股票的最大的利润 = Math.max(昨天就持有,前天不持有且今天买入),i-2表示前天,要做越界判断
      memo[i][1] = Math.max(memo[i-1][1],memo[i-2>0?i-2:0][0] - prices[i]);

      下面上代码:

      Java版本

        public int maxProfit(int[] prices) {
            if(prices == null || prices.length <=1) return 0;
            //记忆数组memo
            int[][] memo = new int[prices.length][2];
            //memo[i][0]表示第i天不持有股票的最大利润,memo[i][1]表示第i天持有股票的最大的利润
            memo[0][0] = 0;
            memo[0][1] = - prices[0];//第一天持有股票的利润
    
            for(int i=1;i<prices.length;i++){
                memo[i][0] = Math.max(memo[i-1][0],memo[i-1][1] + prices[i]);
                memo[i][1] = Math.max(memo[i-1][1],memo[i-2>0?i-2:0][0] - prices[i]);
            }
            //最后一天不持有股票时的利润最大
            return memo[prices.length-1][0];
        }

       JS版本

    var maxProfit = function(prices) {
        if(prices == null || prices.length <= 1) return 0;
        //记忆数组
        let memo = [];
        for(let i=0;i<prices.length;i++){
            memo.push([]);
        }
        //memo[i][0]表示第i天不持有股票的最大利润,memo[i][1]表示第i天持有股票的最大的利润
        memo[0][0] = 0;
        memo[0][1] = - prices[0];
        for(let i=1;i<prices.length;i++){
            //第i天不持有股票的最大利润 = Math.max(昨天就不持有,昨天持有且今天卖出)
            memo[i][0] = Math.max(memo[i-1][0],memo[i-1][1]+prices[i]);
            //第i天持有股票的最大的利润 = Math.max(昨天就持有,前天不持有且今天买入),i-2表示前天,要做越界判断
            memo[i][1] = Math.max(memo[i-1][1],memo[i-2>0?i-2:0][0] - prices[i]);
        }
        return memo[prices.length-1][0];
    };
  • 相关阅读:
    SolrCloud-5.2.1 集群部署及测试
    提问的艺术
    Zookeeper集群部署
    Linux基本操作命令总结
    LeetCode——Gray Code
    LeetCode——Find the Duplicate Number
    如何拿到国内IT巨头的Offer
    LeetCode—— Median of Two Sorted Arrays
    LeetCode——Merge k Sorted Lists
    CSS常见Bugs及解决方案列表
  • 原文地址:https://www.cnblogs.com/bobobjh/p/14415307.html
Copyright © 2011-2022 走看看