You are given an array prices where prices[i] is the price of a given stock on day i.
Find the maximum profit you can achieve. You may complete at most two transactions.
You may not engage in multiple transactions at the same time: you must sell the stock before you buy again.
Function Signature
def max_profit(prices: list[int]) -> int:
Rules
-
Days are 0-indexed, so
prices[0]
is the first day. A transaction buys one share on one day and sells it on a later day.
-
You hold at most one share at any time, so the second transaction cannot buy before the first one has sold.
-
Zero, one or two transactions are allowed. If no transaction makes money, return
0
.
-
Return only the total profit, not the trade days.
Constraints
-
1 <= len(prices) <= 10^5
-
0 <= prices[i] <= 10^5
Examples
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Buy at index 3 (price 0) and sell at index 5 (price 3) for a profit of 3, then buy at index 6 (price 1) and sell at index 7 (price 4) for another 3. The best single trade earns only 4 (buy at 0, sell at 4), so two trades do better.
Input: prices = [1,2,3,4,5]
Output: 4
One trade from price 1 to price 5 earns 4. Splitting the rise into two trades also totals 4, so a second trade adds nothing.
Input: prices = [7,6,4,3,1]
Output: 0
The price falls every day, so every possible trade loses money. Making no transactions gives a profit of 0.