一、题目描述:
leetcode-cn.com/problems/be…
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
****示例 1:
输入:prices = [3,3,5,0,0,3,1,4]
输出:6
解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
二、思路分析:
- 递归 + 记忆化搜索
- 三种情况:
- 当天不进行买卖
- 前一天持有股票:今天可以卖出股票 与 不进行买卖取最大值
- 前一天不持有股票:今天购买股票 与 不进行买卖取最大值
三、AC 代码:
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
const dp = new Array(prices.length + 1).fill(null).map(_ => new Array(3).fill(null).map(_ => []))
function getMaxProfitInRange(index, time, status) {
if (index === prices.length) {
return 0
}
if (time === 2) {
return 0
}
if(dp[index][time][status]!==undefined){
return dp[index][time][status]
}
// hold
let max = getMaxProfitInRange(index + 1, time, status)
if (status) {
// sale
max = Math.max(max, getMaxProfitInRange(index + 1, time + 1, 0) + prices[index])
} else {
// buy
max = Math.max(max, getMaxProfitInRange(index + 1, time, 1) - prices[index])
}
dp[index][time][status] = max
return max
}
return getMaxProfitInRange(0, 0, 0)
};