Maximum Profit from Two Stock Transactions
Dynamic ProgrammingAuto-graded · 25 test casesLast updated
Tests dynamic programming with state transitions to find optimal profit from up to two non-overlapping buy-sell trades given daily stock prices.
You have access to historical daily stock prices. Your goal is to determine the largest profit you can earn by making up to two separate buy-sell transactions.
Write a function that takes a list of integers representing stock prices on consecutive days and returns the maximum profit achievable.
Rules
- Each transaction consists of buying one share and later selling it
- You cannot hold more than one share simultaneously (you must sell before buying again)
- You may complete zero, one, or two transactions total
- The same day may be used for both selling from one transaction and buying for the next
- If no profitable opportunity exists, return 0
Constraints
1 <= len(prices) <= 10^50 <= prices[i] <= 10^5
Examples
Example 1
Input: max_profit_two_trades([2, 5, 1, 4, 9, 3, 7])
Output: 12
Example 2
Input: max_profit_two_trades([9, 7, 4, 1])
Output: 0
Example 3
Input: max_profit_two_trades([1, 2, 3, 4, 5])
Output: 4
Hints
Hint 1
Track the best possible balance after each trading action: first purchase, first sale, second purchase, second sale
Hint 2
When buying the second share, you can use the profit earned from the first completed transaction
Hint 3
Initialize buy states to negative infinity (impossible until executed) and sell states to zero (doing nothing is always valid)
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the trading process as a sequence of states. At any point in time, you occupy one of four positions:
- After first purchase: You hold one share from the first transaction
- After first sale: You completed one transaction and hold no shares
- After second purchase: You hold one share from the second transaction
- After second sale: You completed both transactions
Maintain four variables tracking the best cash balance achievable in each state:
b1: optimal balance after making the first purchase (negative, since you spent money)s1: optimal balance after completing the first transactionb2: optimal balance after making the second purchase (uses profit from first trade)s2: optimal balance after completing both transactions
Process each price sequentially and update all four states based on whether taking action today improves the balance:
- For
b1: either keep the previous best first-purchase balance, or buy today at pricep(balance becomes-p) - For
s1: either keep the previous best first-sale balance, or sell today (addptob1) - For
b2: either keep the previous best second-purchase balance, or buy today (subtractpfroms1) - For
s2: either keep the previous best second-sale balance, or sell today (addptob2)
Initialize buy states to negative infinity (impossible before execution) and sell states to zero (no action is always valid).
Why This Works
Each variable represents the maximum profit achievable through all valid action sequences ending in that particular state. When computing b2, subtracting from s1 effectively carries forward the profit from the first completed transaction, ensuring the two trades remain properly sequenced and non-overlapping.
Updating states in the given order within each iteration naturally handles same-day transitions: selling and rebuying on the same day produces zero net change, which never beats a genuinely profitable option. The final value s2 captures the best outcome from zero, one, or two transactions.
Complexity
Time: O(n) — single pass through the price array with constant work per element
Space: O(1) — only four scalar variables regardless of input size
Solution
from typing import List
def max_profit_two_trades(prices: List[int]) -> int:
b1 = b2 = float("-inf")
s1 = s2 = 0
for p in prices:
b1 = max(b1, -p)
s1 = max(s1, b1 + p)
b2 = max(b2, s1 - p)
s2 = max(s2, b2 + p)
return int(s2)