Best Time to Buy and Sell Stock III
Find the maximum profit with at most two transactions. You may not engage in multiple transactions simultaneously (you must sell the stock before you buy again).
Best Time to Buy and Sell Stock III

Find the maximum profit with at most two transactions. You may not engage in multiple transactions simultaneously (you must sell the stock before you buy again).

Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Input
arr =[3,3,5,0,0,3,1,4]

Initialize: buy1=INF, buy2=INF, sell1=0, sell2=0

3
3
5
0
0
3
1
4
Transaction 1
buy1:INF
sell1:0
Transaction 2
buy2:INF
sell2:0
Max Profit
0
Key Insight: buy2 = price - sell1 represents the effective cost of the second buy after applying the profit from the first transaction. This allows tracking both transactions in a single pass.
Variables
VariableValue
buy1INF
buy2INF
sell10
sell20
DepthFunction Call
Stack empty
0/41