题目链接:309. 买卖股票的最佳时机含冷冻期
题目描述
给定一个整数数组prices
,其中第 prices[i]
表示第 i
天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: prices = [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
示例 2:
输入: prices = [1] 输出: 0
提示:
1 <= prices.length <= 5000
0 <= prices[i] <= 1000
文章讲解:代码随想录
视频讲解:动态规划来决定最佳时机,这次有冷冻期!| LeetCode:309.买卖股票的最佳时机含冷冻期_哔哩哔哩_bilibili
题解1:动态规划
思路:使用动态规划法求解买卖股票问题。
动态规划分析:
- dp 数组以及下标的含义:dp 是一个二维数组,每行三个元素。dp[i][0] 表示第 i 天持有股票所得的最大现金,dp[i][1] 代表第 i 天保持卖出股票所得的最大现金,dp[i][2] 代表第 i 天卖出股票所得的最大现金。
- 递推公式:dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]),dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][2]),dp[i][2] = Math.max(dp[i - 1][0] + prices[i])。
- dp 数组初始化:dp[0][0] = -prices[0],dp[0][1] = 0,dp[0][2] = 0。
- 遍历顺序:从前到后。
- 打印 dp 数组:以输入 [1,2,3,0,2] 为例,dp 数组为 [ [ -1, 0, 0 ], [ -1, 0, 1 ], [ -1, 1, 2 ], [ 1, 2, -1 ], [ 1, 2, 3 ] ]。
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const dp = new Array(prices.length).fill().map(() => new Array(3));
dp[0][0] = -prices[0];
dp[0][1] = 0;
dp[0][2] = 0;
for (let i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][2]);
dp[i][2] = Math.max(dp[i - 1][0] + prices[i]);
}
return Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2]);
};
分析:时间复杂度为 O(n),空间复杂度为 O(n)。
收获
本题状态更多,要分析每个状态的含义和转移。