
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Best Time to Buy and Sell Stock III
								Certification: Advanced Level
								Accuracy: 0%
								Submissions: 0
								Points: 15
							
							Write a C program to find the maximum profit you can achieve from buying and selling stocks. You are given an array prices where prices[i] is the price of a given stock on the ith 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).
Example 1
- Input: prices = [3,3,5,0,0,3,1,4]
 - Output: 6
 - Explanation: 
- Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 
 - Buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. 
 - Total profit = 3 + 3 = 6. 
 - This uses exactly 2 transactions and gives maximum profit.
 
 - Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 
 
Example 2
- Input: prices = [1,2,3,4,5]
 - Output: 4
 - Explanation: 
- Buy on day 1 (price = 1) and sell on day 2 (price = 2), profit = 2-1 = 1. 
 - Buy on day 2 (price = 2) and sell on day 5 (price = 5), profit = 5-2 = 3. 
 - Total profit = 1 + 3 = 4. 
 - You can also buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4.
 
 - Buy on day 1 (price = 1) and sell on day 2 (price = 2), profit = 2-1 = 1. 
 
Constraints
- 1 ≤ prices.length ≤ 10^5
 - 0 ≤ prices[i] ≤ 10^5
 - You can complete at most 2 transactions
 - Time Complexity: O(n)
 - Space Complexity: O(1)
 
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use state machine approach with four states for two transactions
 - Track buy1, sell1, buy2, sell2 for maximum profit at each state
 - buy1: maximum profit after first buy
 - sell1: maximum profit after first sell
 - buy2: maximum profit after second buy
 - sell2: maximum profit after second sell
 - Update states in single pass through prices array