KatInterview

Best Profit from One or Two Stock Transactions

Dynamic ProgrammingAuto-graded · 22 test cases
HardAuto-gradedDynamic Programmingarraysgreedystate-machine

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