KatInterview

Maximum Profit from Two Stock Transactions

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingarraysstate-machineoptimization

Last 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^5
  • 0 <= 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)