309.最佳买卖股票时机含冷冻期
// 一维数组空间优化
const maxProfit = (prices) => {const n = prices.lengthconst dp = new Array(4).fill(0)dp[0] = -prices[0]for (let i = 1; i < n; i ++) {const temp = dp[0] // 缓存上一次的状态const temp1 = dp[2]dp[0] = Math.max(dp[0], Math.max(dp[3] - prices[i], dp[1] - prices[i])) // 持有状态dp[1] = Math.max(dp[1], dp[3]) // 今天不操作且不持有股票dp[2] = temp + prices[i] // 今天卖出股票dp[3] = temp1 // 冷冻期}return Math.max(...dp)
};
第一想法
困难
收获
1
/*** @param {number[]} prices* @param {number} fee* @return {number}*/
var maxProfit = function(prices, fee) {const len = prices.length;// 创建dp数组const dp = new Array(len).fill([0, 0]);// dp数组初始化dp[0] = [-prices[0], 0];for (let i = 1; i < len; i++) {// 更新dp[i]dp[i] = [Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]),Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]-fee),//在卖出时加一笔手续费];}return dp[len - 1][1];
};
第一想法
在卖出时加一笔手续费