Best Time to Buy and Sell Stock III - Problem
You're a stock trader with a special constraint: you can only make at most two transactions (buy-sell pairs) to maximize your profit.
Given an array prices where prices[i] represents the stock price on day i, find the maximum profit you can achieve with at most 2 complete transactions.
Important Rules:
- You must sell before buying again (no simultaneous transactions)
- A transaction consists of buying and then selling one share
- You can choose to make 0, 1, or 2 transactions
Example: If prices = [3,3,5,0,0,3,1,4], you can buy at 3, sell at 5 (profit=2), then buy at 0, sell at 4 (profit=4) for total profit of 6.
Input & Output
example_1.py โ Basic Case
$
Input:
prices = [3,3,5,0,0,3,1,4]
โบ
Output:
6
๐ก Note:
Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 3. Total profit = 6.
example_2.py โ Single Transaction Better
$
Input:
prices = [1,2,3,4,5]
โบ
Output:
4
๐ก Note:
Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4. Making a second transaction would not increase profit.
example_3.py โ No Profit Possible
$
Input:
prices = [7,6,4,3,1]
โบ
Output:
0
๐ก Note:
Prices only decrease, so no profitable transactions are possible.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize States
Start with four states tracking maximum profit at each trading stage
2
Process Each Day
For each price, decide whether to transition states or maintain current position
3
State Updates
Update each state by choosing maximum between staying or taking action
4
Extract Result
Final result is in sell2 state, representing maximum profit from at most 2 complete transactions
Key Takeaway
๐ฏ Key Insight: We don't need to track all possible transaction combinations - just maintain the optimal profit for each trading state and transition between them optimally.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, updating four states at each step
โ Linear Growth
Space Complexity
O(1)
Only using four variables to track the states
โ Linear Space
Constraints
- 1 โค prices.length โค 105
- 0 โค prices[i] โค 105
- At most 2 transactions allowed
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code