Day51~121. 买卖股票的最佳时机、122.买卖股票的最佳时机II

100 阅读2分钟

摘要

本文主要介绍了LeetCode动态规划的几个题目,包括121. 买卖股票的最佳时机、122.买卖股票的最佳时机II。

1、121.买卖股票的最佳时机

1.1 思路

  • dp 数组以及下标的含义

    • dp[0][i] 表示第 i 天不持有股票的最大利润;dp[1][i] 表示第 i 天持有股票的最大利润;
  • 递推公式

    • dp[0][i] = Math.max(dp[0][i-1], dp[1][i-1] + prices[i])

      • i-1 天就不持有股票,那么就保持现状,所得现金就是昨天不持有股票的所得现金 即:dp[0][i - 1]
      • i 天卖出股票,所得现金就是按照今天股票价格卖出后所得现金即:dp[1][i-1] + prices[i]
    • dp[1][i] = Math.max(dp[1][i-1], -prices[i])

      • i-1 天就持有股票,那么就保持现状,所得现金就是昨天持有股票的所得现金即:dp[1][i-1]
      • i 天买入股票,所得现金就是买入今天的股票后所得现金即:-prices[i]
  • dp 数组如何初始化

    • dp[0][0] = 0dp[1][0] = -prices[0]
  • dp 数组遍历顺序

    • 从前向后遍历

1.2 代码

    public int maxProfit(int[] prices) {
        int len = prices.length;
        int[][] dp = new int[2][len];
        dp[0][0] = 0; 
        dp[1][0] = -prices[0]; 
        
        for(int i=1; i<len; i++) {
            dp[0][i] = Math.max(dp[0][i-1], dp[1][i-1] + prices[i]);
            dp[1][i] = Math.max(dp[1][i-1], - prices[i]);
        }
        return dp[0][len-1];
    }

2、122.买卖股票的最佳时机II

2.1 思路

  • dp 数组以及下标的含义

    • dp[0][i] 表示第 i 天不持有股票的最大利润;dp[1][i] 表示第 i 天持有股票的最大利润;
  • 递推公式

    • dp[0][i] = Math.max(dp[0][i-1], dp[1][i-1] + prices[i])

    • dp[1][i] = Math.max(dp[1][i-1], dp[0][i-1] - prices[i])

      • 注意这里是和121. 买卖股票的最佳时机唯一不同的地方
  • dp 数组如何初始化

    • dp[0][0] = 0dp[1][0] = -prices[0]
  • dp 数组遍历顺序

    • 从前向后遍历
  • 打印 dp 数组

2.2 代码

    public int maxProfit(int[] prices) {
        int len = prices.length;
        int[][] dp = new int[2][len];
        dp[0][0] = 0; 
        dp[1][0] = -prices[0]; 
        
        for(int i=1; i<len; i++) {
            dp[0][i] = Math.max(dp[0][i-1], dp[1][i-1] + prices[i]);
            dp[1][i] = Math.max(dp[1][i-1], dp[0][i-1] - prices[i]);
        }
        return dp[0][len-1];
    }

参考资料

代码随想录-121. 买卖股票的最佳时机

代码随想录-122.买卖股票的最佳时机II