Sponsored
Sponsored
This approach utilizes dynamic programming with four state variables to track the profit in various stages of transactions: before the first buy, after the first buy (before the sell), after the first sell (before the second buy), and after the second buy (before the final sell). By iterating over the prices array, we update these states with the maximum profit achievable at each step.
Time Complexity: O(n), where n is the number of days (prices length).
Space Complexity: O(1), constant space used regardless of input size.
1using System;
2
3public class StockProfit {
4 public static int MaxProfit(int[] prices) {
5 int firstBuy = int.MinValue, firstSell = 0, secondBuy = int.MinValue, secondSell = 0;
6
7 foreach (int price in prices) {
8 firstBuy = Math.Max(firstBuy, -price);
9 firstSell = Math.Max(firstSell, firstBuy + price);
10 secondBuy = Math.Max(secondBuy, firstSell - price);
11 secondSell = Math.Max(secondSell, secondBuy + price);
12 }
13 return secondSell;
14 }
15
16 public static void Main() {
17 int[] prices = new int[] { 3, 3, 5, 0, 0, 3, 1, 4 };
18 Console.WriteLine("Max Profit: " + MaxProfit(prices));
19 }
20}
This C# solution employs a method with loop to iterate over stock prices, using logic to develop and update four critical state variables. The states depict the profit potential at specific transaction stages.
This approach involves creating two arrays that store the maximum profit achievable from the left side to each index and from each index to the right in the prices array. Combining these two arrays helps derive the total maximum profit achievable through two transactions.
Time Complexity: O(n), as we iterate twice through prices.
Space Complexity: O(n), due to the use of two auxiliary arrays.
1
Java solution develops intermediate revenue profiles from forward and backward traversals. Merging these arrays reveals the utmost financially positive junction for two separate transactions.