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
Best Time to Buy and Sell Stock III INPUT Stock Prices Over Days 5 4 3 2 1 0 0 1 2 3 4 5 6 7 prices array: 3 3 5 0 0 3 1 4 [0] [1] [2] [3] [4] [5] [6] [7] Max 2 transactions allowed Must sell before buying again ALGORITHM STEPS 1 Track 4 States buy1, sell1, buy2, sell2 buy1 -INF sell1 0 buy2 -INF sell2 0 2 Update Each Day For each price, update states buy1 = max(buy1, -price) sell1 = max(sell1, buy1+price) buy2 = max(buy2, sell1-price) sell2 = max(sell2, buy2+price) 3 Key Transitions Buy at 0, Sell at 3 (profit 3) Buy at 1, Sell at 4 (profit 3) Transaction 1 Buy@0 Sell@3 Transaction 2 Buy@1 Sell@4 4 Return sell2 Max profit with at most 2 txns O(n) time FINAL RESULT Two Optimal Transactions Transaction 1 BUY Day 3 $0 --> SELL Day 5 $3 +$3 Transaction 2 BUY Day 6 $1 --> SELL Day 7 $4 +$3 TOTAL PROFIT $6 Output: 6 OK - Maximum achieved! Key Insight: Use Dynamic Programming with 4 state variables to track the best profit at each stage: - buy1: Max profit after first buy | sell1: Max profit after first sell - buy2: Max profit after second buy (using sell1 profit) | sell2: Max profit after second sell TutorialsPoint - Best Time to Buy and Sell Stock III | Optimal DP Solution
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