Sponsored
Sponsored
This approach uses dynamic programming to track three states on each day: holding, not holding with cooldown, and not holding without cooldown. The idea is to decide the best action for any day based on the previous day's states. At each step, calculate the maximum profit for holding a stock, selling it, or being idle.
Time Complexity: O(n), where n is the number of days. Each day's prices are visited once.
Space Complexity: O(1), since only a fixed amount of extra space is used.
1function maxProfit(prices) {
2 if (prices.length === 0) return 0;
3 let hold = -prices[0], sell = 0, cooldown = 0;
4 for (let i = 1; i < prices.length; i++) {
5 let prev_sell = sell;
6 sell = hold + prices[i];
7 hold = Math.max(hold, cooldown - prices[i]);
8 cooldown = Math.max(cooldown, prev_sell);
9 }
10 return Math.max(sell, cooldown);
11}
12
13console.log("Max Profit:", maxProfit([1, 2, 3, 0, 2]));
The JavaScript function maxProfit
operates by iterating through the price list and updates state variables hold
, sell
, and cooldown
to manage possible transitions and maximize profits.
This approach involves a recursive solution that tracks the profit by exploring all possible transactions. To optimize the solution, memoization is used to store and reuse results of repeated states to avoid redundant calculations.
Time Complexity: O(n), where n is the number of days. Thanks to memoization, each state is computed once.
Space Complexity: O(n), for the memoization table.
This solution implements a recursive strategy in Java with memoization. It checks each state for buy-sell possibilities and uses memoization to avoid recomputation.