可以买卖两次,两次股票的购买与出售不要交叉,必须买卖完一支,再进行另外一支
这道题的关键在于如何使用动态规划来记录两个交易的最大收益。为了做到这一点,可以维护四个变量,分别表示在某些状态下的最大收益:
firstBuy:第一次买入后的最大收益。firstSell:第一次卖出后的最大收益。secondBuy:第二次买入后的最大收益。secondSell:第二次卖出后的最大收益。
var maxProfit = function (prices) {
let firstBuy = -Infinity
let firstSell = 0
let secondBuy = -Infinity
let secondSell = 0
for (let price of prices) {
// 负的最大,自然是正的最小
firstBuy = Math.max(firstBuy, -price)
firstSell = Math.max(firstSell, firstBuy + price)
secondBuy = Math.max(secondBuy, firstSell - price)
secondSell = Math.max(secondSell, secondBuy + price)
}
return secondSell
};
-
时间复杂度: O(n),其中 n 是价格数组的长度,我们只需要遍历一次数组。
-
空间复杂度: O(1),只用了常数个额外的变量。