Best Time to Buy and Sell Stock with Cooldown LeetCode solution in JavaScript

1
/**
2
* @param {number[]} prices
3
* @return {number}
4
*/
5
var maxProfit = function (prices) {
6
let dp = {};
7
let recursiveProfit = (index, buy) => {
8
if (index >= prices.length) {
9
return 0;
10
}
11
if (dp[index + "_" + buy]) return dp[index + "_" + buy];
12
if (buy) {
13
dp[index + "_" + buy] = Math.max(
14
-prices[index] + recursiveProfit(index + 1, 0),
15
0 + recursiveProfit(index + 1, 1)
16
);
17
return dp[index + "_" + buy];
18
} else {
19
dp[index + "_" + buy] = Math.max(
20
prices[index] + recursiveProfit(index + 2, 1),
21
0 + recursiveProfit(index + 1, 0)
22
);
23
return dp[index + "_" + buy];
24
}
25
};
26
return recursiveProfit(0, 1);
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0