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.
1public class StockProfit {
2 public static int maxProfit(int[] prices) {
3 if (prices.length == 0) return 0;
4 int firstBuy = Integer.MIN_VALUE, firstSell = 0, secondBuy = Integer.MIN_VALUE, secondSell = 0;
5
6 for (int price : prices) {
7 firstBuy = Math.max(firstBuy, -price);
8 firstSell = Math.max(firstSell, firstBuy + price);
9 secondBuy = Math.max(secondBuy, firstSell - price);
10 secondSell = Math.max(secondSell, secondBuy + price);
11 }
12 return secondSell;
13 }
14
15 public static void main(String[] args) {
16 int[] prices = {3, 3, 5, 0, 0, 3, 1, 4};
17 System.out.println("Max Profit: " + maxProfit(prices));
18 }
19}
In Java, this solution leverages built-in utilities for calculation. It uses a similar four-state setup to C++ for tracking transaction phases and profit maximization exploration.
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.