← Questions

Best time to buy and sell stock: one trade, then two

0
UberCodingLast asked Feb 2026

A coding interview question asked in Uber's coding round, last asked Feb 2026. It tests dynamic programming, arrays and greedy.

You get a stock's price for each day. Return the most profit you can make by buying and later selling, first with a single trade, then with up to two trades. You hold at most one share at a time, so a second buy must come after the first sell.

Part 1: one trade

Unless you agree on a different interface with the interviewer, assume:

  • max_profit_one(prices: list[int]) -> int — pick one day to buy and a later day to sell. Return 0 if no trade makes money.
max_profit_one([7, 1, 5, 3, 6, 4])  ->  5    # buy at 1, sell at 6
max_profit_one([7, 6, 4, 3, 1])     ->  0

Part 2: at most two trades

  • max_profit_two(prices: list[int]) -> int — up to two buy-then-sell trades that do not overlap.
max_profit_two([3, 3, 5, 0, 0, 3, 1, 4])  ->  6    # buy 0 sell 3, buy 1 sell 4
max_profit_two([1, 2, 3, 4, 5])           ->  4    # one trade is best
max_profit_two([7, 1, 5, 3, 6, 4])        ->  7    # buy 1 sell 5, buy 3 sell 6

Constraints

  • 1 <= len(prices) <= 10^5, 0 <= prices[i] <= 10^4.

Clarifying questions

  • Can I buy and sell on the same day? (It earns nothing.)
  • Must I make a trade, or is no trade allowed (profit 0)?
  • Can the second buy happen on the day of the first sell?
  • Should I return the days as well as the profit?

What a strong answer covers

  • Part 1: one pass keeping the lowest price so far and the best price - lowest. O(n) time, O(1) space.
  • Part 2: four running states (after first buy, after first sell, after second buy, after second sell), updated each day, O(n) and O(1). Or the split approach: best single trade ending by day i plus best single trade starting after i, with two arrays.
  • Why the brute force over all pairs, O(n²) for one trade and worse for two, does not scale.
  • Tests: falling prices, one day, flat prices, the best two trades overlapping the best single trade.

Follow-ups

  • At most k trades: a DP over days and trades, O(n · k), and when k >= n / 2 it reduces to taking every rise.
  • Each trade pays a fixed fee.
  • After selling you must wait one day before buying again.

Where it's asked

  • Uber · Coding · Last asked Feb 202660 min · Two rounds; one is often object-oriented design (a parking lot, a meeting scheduler, an expression evaluator) · No AI, except a newer AI-assisted debugging round in some senior loops

What it tests

dynamic programming · arrays · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding