Best Time to Buy and Sell Stock III
Implement maxProfit
Given daily stock `prices`, complete at most two buy-sell transactions — never holding more than one share at a time, and always selling the current share before buying the next one. Maximize total profit; skipping trading entirely (profit 0) is always allowed.
The single-transaction version tracks one running number: the best profit reachable by day `i`. Adding a second transaction means that number now has to fork into four, one per stage of the two-transaction journey — holding after buy one, settled after sell one, holding again after buy two, settled after sell two. Each stage can only be reached by first passing through the stage before it, so sweeping through the prices once and refreshing all four numbers in that fixed order — buy one, sell one, buy two, sell two — keeps every stage built only on information that's already correct by the time it's used.
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ prices.length ≤ 10 - ●
0 ≤ prices[i] ≤ 1000 - ●
at most two buy-sell transactions are allowed; you must sell before buying again
prices =
[3, 3, 5, 0, 0, 3, 1, 4]