Maximum stock trading profit with at most two buy-and-sell transactions
OracleSoftware Engineer · OtherLast updated
A stock trading optimization problem: given daily prices, find the maximum profit using at most two buy-then-sell transactions while holding at most one share at a time. It tests reasoning about splitting the price history into non-overlapping trades and handling falling, flat or steadily rising prices.
You are given a list prices, where prices[i] is the price of one share of a stock on day i. You may complete at most two transactions, where a transaction means buying one share and later selling it. Return the maximum total profit you can achieve.
Function Signature
def max_profit_two_transactions(prices: List[int]) -> int:
Rules
- You can hold at most one share at a time, so you must sell before buying again.
- A sale and the next purchase may happen on the same day.
- Fewer than two transactions, or none at all, is allowed; if no trade makes money, return
0.
Constraints
1 <= len(prices) <= 10^50 <= prices[i] <= 10^5
Examples
Example 1
Input: prices = [2, 5, 1, 4, 9, 3, 7]
Output: 12
Buy at 1 on day 2 and sell at 9 on day 4 for 8, then buy at 3 on day 5 and sell at 7 on day 6 for 4.
Example 2
Input: prices = [9, 7, 4, 1]
Output: 0
Prices only fall, so no transaction is profitable.
Example 3
Input: prices = [1, 2, 3, 4, 5]
Output: 4
A single transaction from 1 to 5 already achieves the maximum; a second one adds nothing.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.