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 3 (price = 0) and sell on day 5 (price = 3) for +3, then buy on day 6 (price = 1) and sell on day 7 (price = 4) for +3. Two transactions give 3 + 3 = 6.
Example 2
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy at 1 and sell at 5 for a profit of 4. Splitting it into two trades cannot beat one trade across a steadily rising price.
Example 3
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Prices only fall, so no transaction makes money and the answer is 0.
Track four running best values as you scan the prices: the best position after the first buy, after the first sell, after the second buy, and after the second sell. Each depends only on the previous state and the current price, so one pass suffices.
Run checks all cases above. Submit evaluates all test cases.