// 一维数组空间优化
const maxProfit = (prices) => {
const n = prices.length
const 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)
};
/**
* @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];
};
在卖出时加一笔手续费