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.
1public class Solution {
2 public int maxProfit(int[] prices) {
3 if (prices.length == 0) return 0;
4 int hold = -prices[0], sell = 0, cooldown = 0;
5 for (int i = 1; i < prices.length; i++) {
6 int prev_sell = sell;
7 sell = hold + prices[i];
8 hold = Math.max(hold, cooldown - prices[i]);
9 cooldown = Math.max(cooldown, prev_sell);
10 }
11 return Math.max(sell, cooldown);
12 }
13 public static void main(String[] args) {
14 Solution sol = new Solution();
15 int[] prices = {1, 2, 3, 0, 2};
16 System.out.println("Max Profit: " + sol.maxProfit(prices));
17 }
18}
The Java implementation follows the same logic as the C and C++ solutions. It iterates through the price array and updates the state variables. Math.max
is used for comparing 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.
The JavaScript recursive approach uses memoization to store interim results in the memo
object to prevent recalculation of states, thus optimizing performance while ensuring all buy-sell possibilities are accounted for.