Best Profit from One or Two Stock Transactions
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests dynamic programming and greedy strategies to compute optimal profit from array-based buy/sell scheduling with transaction limits.
You receive an array prices representing the daily price of a stock, where prices[i] indicates the cost on day i (zero-indexed).
Your goal is to determine the maximum profit achievable under two different transaction limits. A transaction consists of purchasing the stock on one day and selling it on a later day. You cannot hold multiple shares simultaneously—you must sell before purchasing again.
Return a list of two integers: [max_profit_one_trade, max_profit_two_trades].
Part 1: Single Transaction Limit
Compute the highest profit you can obtain by executing at most one buy-sell transaction. If no profitable opportunity exists, the result is 0.
Part 2: Two Transaction Limit
Compute the highest total profit achievable with at most two separate transactions. Each transaction must be completed (buy then sell) before the next one begins. If fewer than two transactions yield better profit, the answer reflects that optimal choice.
Your solution must run in O(n) time with O(1) or O(n) additional space.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Examples
Example 1
Input: best_profit_two_limits([7, 1, 5, 3, 6, 4])
Output: [5, 7]
Example 2
Input: best_profit_two_limits([3, 3, 5, 0, 0, 3, 1, 4])
Output: [4, 6]
Example 3
Input: best_profit_two_limits([7, 6, 4, 3, 1])
Output: [0, 0]
Example 4
Input: best_profit_two_limits([1, 2, 3, 4, 5])
Output: [4, 4]
Hints
Hint 1
For one transaction, track the lowest price seen so far and compute profit if you sold today at each step.
Hint 2
For two transactions, model your cash balance through four states: after first buy, after first sell, after second buy, after second sell.
Hint 3
Update all four state variables in sequence for each price—allowing same-day buy-sell transitions that contribute zero profit but maintain correctness.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1: One Transaction
Scan the array left-to-right while maintaining the minimum price encountered so far. At each position, calculate the profit if we sold at the current price after buying at the historical minimum. Track the maximum such profit.
Why it works: For any selling day, the optimal buying day is the cheapest day that came before it. By updating the minimum price after computing profit at each step, we ensure the buy always precedes the sell.
Part 2: Two Transactions
Model the problem as a state machine with four states representing net cash balance:
- first_buy: balance after purchasing the first share (negative cost)
- first_sell: balance after selling the first share (profit from first transaction)
- second_buy: balance after purchasing the second share (first profit minus second cost)
- second_sell: balance after selling the second share (total profit from both transactions)
For each price, update all four states in order:
first_buy = max(first_buy, -price)— keep previous state or buy todayfirst_sell = max(first_sell, first_buy + price)— keep previous or sell first share todaysecond_buy = max(second_buy, first_sell - price)— keep previous or buy second share todaysecond_sell = max(second_sell, second_buy + price)— keep previous or sell second share today
Initialize with day 0: first_buy = second_buy = -prices[0] and first_sell = second_sell = 0.
Why it works: Each state transition considers either staying in the current state (no action) or moving from the previous state by trading at today's price. The max operation ensures we always take the optimal path. Updating in sequence allows same-day buy-sell pairs that contribute zero net profit—these never create invalid schedules or inflate the result.
The final second_sell value automatically handles cases with fewer than two beneficial transactions: if one transaction suffices, the "second" transaction effectively becomes a zero-profit same-day round trip.
Complexity
- Time: O(n) — two single passes through the array with constant work per element
- Space: O(1) — only scalar variables maintained
Solution
from typing import List
def best_profit_two_limits(prices: List[int]) -> List[int]:
if not prices:
return [0, 0]
min_price = prices[0]
single_trade_profit = 0
for price in prices[1:]:
single_trade_profit = max(single_trade_profit, price - min_price)
min_price = min(min_price, price)
first_buy = -prices[0]
first_sell = 0
second_buy = -prices[0]
second_sell = 0
for price in prices[1:]:
first_buy = max(first_buy, -price)
first_sell = max(first_sell, first_buy + price)
second_buy = max(second_buy, first_sell - price)
second_sell = max(second_sell, second_buy + price)
return [single_trade_profit, second_sell]