DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.
DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.DowngradedOur downstream service providers are currently experiencing outages, and our engineering team is actively working on a resolution. Some services—including the Solver, Partner, and Tools—are temporarily degraded with higher latency and lower bandwidth. Rest assured, Intervipedia, Solutions, and the Question Bank features are not impacted and remain fully operational.
The Question
Coding

Best Time to Buy and Sell Stock III

Given an array prices where prices[i] is the price of a given stock on the i-th day, design an algorithm to find the maximum profit you can achieve with at most two transactions. You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Your solution should ideally run in linear time and use constant extra space.
Java
DP
Questions & Insights

Clarifying Questions

What is the maximum size of the `prices` array? This helps determine if an O(n^2) approach is acceptable or if we must aim for O(n).
What is the range of values for each price? We need to ensure that our variables (like those storing profit) don't overflow, although standard 32-bit integers are usually sufficient for stock problems unless prices are extremely high.
Can the input array be empty or have only one element? If so, the profit should naturally be 0 since a transaction requires at least two different days (or at least a buy and a sell).
Does "at most two transactions" mean we can perform zero or one transaction? Yes, the goal is to maximize profit within the constraint of 0, 1, or 2 completed transactions.

Assumptions

The array size N can be up to 10^5, requiring an O(n) solution.
Prices are non-negative integers.
Transactions must be sequential: Buy1 -> Sell1 -> Buy2 -> Sell2.

Thinking Process

State Representation: To track the progress of up to two transactions, we can maintain the "net balance" at four distinct stages: after the first buy, after the first sell, after the second buy, and after the second sell.
The Reinvestment Logic: The key intuition for the second transaction is to treat the profit from the first transaction as a "subsidy" for the second purchase. If we have P_1 profit from the first trade and buy a second stock at price C_2, our effective cost is C_2 - P_1.
Greedy DP Update: As we iterate through the price array once, we update each of the four states. Since we want to maximize the final balance, we use Math.max at each step to decide whether to stay in the current state or transition to it using the current day's price.
Handling "At Most": By initializing the sell profits to 0 and the buy balances to negative infinity, the algorithm naturally handles cases where doing one or zero transactions is better than doing two (e.g., in a strictly decreasing market, the profit will remain 0).
Implementation Breakdown

Problem Set

Functional Requirements: Calculate the maximum profit from at most two non-overlapping stock transactions.
Constraints:
Time Complexity: O(n)
Space Complexity: O(1)
Input: int[] prices
Output: int (max profit)

Approach

Algorithm: One-pass DP (State Machine)
Data Structure: Four scalar variables to track states.
Complexity:
Time: O(n) where n is the length of the prices array.
Space: O(1) as we only store four variables regardless of input size.

Implementation

Wrap Up

Advanced Topics

Generalization to K Transactions: This problem is a specific case (k=2) of the general "Best Time to Buy and Sell Stock IV". For a general k, we would use an array buy[k] and sell[k] and a nested loop.
Readability vs. Performance: While the O(1) space solution is highly performant, a 2D DP table dp[transaction_count][day_count] is sometimes considered more readable for explaining the transitions, though it consumes O(k \cdot n) space.
Streaming Adaptation: This O(1) space approach is ideal for a streaming context where price data arrives one by one, as we don't need to store the history of prices; we only need to maintain the four state variables.