From 2262d1484fbe499636d220b0a7990b15966df181 Mon Sep 17 00:00:00 2001 From: Dhruvi shah <140332592+dhruvishah122@users.noreply.github.com> Date: Mon, 7 Oct 2024 21:06:11 +0530 Subject: [PATCH] Create Best Time to Buy and Sell Stock with Cooldown --- ...t Time to Buy and Sell Stock with Cooldown | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Dynamic-Programming/Best Time to Buy and Sell Stock with Cooldown diff --git a/Dynamic-Programming/Best Time to Buy and Sell Stock with Cooldown b/Dynamic-Programming/Best Time to Buy and Sell Stock with Cooldown new file mode 100644 index 0000000000..7f3ed70c4b --- /dev/null +++ b/Dynamic-Programming/Best Time to Buy and Sell Stock with Cooldown @@ -0,0 +1,24 @@ +var maxProfit = function(prices) { + const memo = {}; // Initialize memoization object + return _maxProfit(prices, 0, false, memo); // Start the recursion with buy index 0 and no stock in hand +} + +var _maxProfit = function(prices, day, hasStock, memo) { + if (day >= prices.length) return 0; // Base case: no more days left + + const key = day + '_' + hasStock; // Using both day and stock status as the key for memoization + if (key in memo) return memo[key]; // Return memoized result if available + + let maxProfit = 0; + // If we have the stock, we can either sell it or continue holding + if (hasStock) { + // Sell the stock and go to the next day with no stock + maxProfit = Math.max(prices[day] + _maxProfit(prices, day + 2, false, memo), _maxProfit(prices, day + 1, true, memo)); + } else { + // If we don't have the stock, we can either buy it or skip the current day + maxProfit = Math.max(-prices[day] + _maxProfit(prices, day + 1, true, memo), _maxProfit(prices, day + 1, false, memo)); + } + + memo[key] = maxProfit; // Memoize the result + return maxProfit; +};