Best Time to Buy and Sell Stock III - Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Input & Output

Example 1 — Two Profitable Transactions
$ 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 = 1), profit = 1. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 3. Total profit = 1 + 3 = 4. Wait, actually: buy on day 0 (price = 3), sell on day 2 (price = 5), profit = 2. Buy on day 3 (price = 0), sell on day 5 (price = 3), profit = 3. Total = 2 + 3 = 5. Actually the optimal is: buy day 3 (price=0), sell day 5 (price=3), profit=3. Buy day 6 (price=1), sell day 7 (price=4), profit=3. Total = 6.
Example 2 — One Transaction Better
$ Input: prices = [1,2,3,4,5]
Output: 4
💡 Note: Buy on day 0 (price = 1) and sell on day 4 (price = 5), profit = 4. Since prices are monotonically increasing, one transaction is optimal.
Example 3 — No Profit Possible
$ Input: prices = [7,6,4,3,1]
Output: 0
💡 Note: Prices are monotonically decreasing, so no profitable transaction is possible.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ prices[i] ≤ 105

Visualization

Tap to expand
Stock Trading: At Most 2 Transactions33500314Day 0Day 1Day 2Day 3Day 4Day 5Day 6Day 7Transaction 1Buy: 0, Sell: 3 → Profit: 3Transaction 2Buy: 1, Sell: 4 → Profit: 3Two non-overlapping transactions allowedTotal Maximum Profit: 3 + 3 = 6🎯 Key: Dynamic programming to track optimal states
Understanding the Visualization
1
Input
Array of stock prices over time
2
Strategy
Find at most 2 transactions for maximum profit
3
Output
Maximum profit achievable
Key Takeaway
🎯 Key Insight: Use state machine DP to track four transaction states efficiently in one pass
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
95.0K Views
High Frequency
~25 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen