Skip to content

Commit 2262d14

Browse files
Create Best Time to Buy and Sell Stock with Cooldown
1 parent 18da83a commit 2262d14

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var maxProfit = function(prices) {
2+
const memo = {}; // Initialize memoization object
3+
return _maxProfit(prices, 0, false, memo); // Start the recursion with buy index 0 and no stock in hand
4+
}
5+
6+
var _maxProfit = function(prices, day, hasStock, memo) {
7+
if (day >= prices.length) return 0; // Base case: no more days left
8+
9+
const key = day + '_' + hasStock; // Using both day and stock status as the key for memoization
10+
if (key in memo) return memo[key]; // Return memoized result if available
11+
12+
let maxProfit = 0;
13+
// If we have the stock, we can either sell it or continue holding
14+
if (hasStock) {
15+
// Sell the stock and go to the next day with no stock
16+
maxProfit = Math.max(prices[day] + _maxProfit(prices, day + 2, false, memo), _maxProfit(prices, day + 1, true, memo));
17+
} else {
18+
// If we don't have the stock, we can either buy it or skip the current day
19+
maxProfit = Math.max(-prices[day] + _maxProfit(prices, day + 1, true, memo), _maxProfit(prices, day + 1, false, memo));
20+
}
21+
22+
memo[key] = maxProfit; // Memoize the result
23+
return maxProfit;
24+
};

0 commit comments

Comments
 (0)