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.
1using System;
2
3public class Solution {
4 public int MaxProfit(int[] prices) {
5 if (prices.Length == 0) return 0;
6 int hold = -prices[0], sell = 0, cooldown = 0;
7 for (int i = 1; i < prices.Length; i++) {
8 int prev_sell = sell;
9 sell = hold + prices[i];
10 hold = Math.Max(hold, cooldown - prices[i]);
11 cooldown = Math.Max(cooldown, prev_sell);
12 }
13 return Math.Max(sell, cooldown);
14 }
15 public static void Main(string[] args) {
16 Solution sol = new Solution();
17 int[] prices = {1, 2, 3, 0, 2};
18 Console.WriteLine("Max Profit: " + sol.MaxProfit(prices));
19 }
20}
C# solution works by iterating through the prices and updating three state variables. It applies similar logic and utilization of Math.Max
to determine profit in possible states of holding, selling, and cooldown.
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.
1
This C version uses a recursive function called solve
that considers each day and whether you can buy or have to sell, using memoization for repetitive states. It attempts both buying and selling actions recursively and stores maximum profits attainable to avoid recomputation.