CodeArchon

easySliding WindowAmazonMetaBloomberg

Market Timing Profit

A trader sees the day-by-day price of a single stock. Picking exactly one buy day and one later sell day, what is the maximum profit?

Given an integer array `prices` where `prices[i]` is the price on day i, return the max profit from one buy / one sell transaction. If no profit is possible, return 0.

Choose approach

7
0
1
1
5
2
3
3
6
4
4
5
1/8
Narrationstep 1 of 8

Track the cheapest price seen so far. For each day, best profit = today's price − cheapest so far.

1def market_timing_profit(prices: list[int]) -> int:
2 min_so_far, best = float("inf"), 0
3 for i, p in enumerate(prices):
4 if p < min_so_far:
5 min_so_far = p
6 elif p - min_so_far > best:
7 best = p - min_so_far
8 return best
Variables
minSoFar=∞
best=0

How to think about it

  1. Brute force (every buy/sell pair) is O(n²).
  2. You never need to look backward — the only buy day worth remembering is the cheapest so far.
  3. Walk once; keep two scalars (minSoFar, best).
  4. Returns 0 if prices only decline (no profitable trade).

Edge cases to catch in interview

  • Monotonic increasing — profit = last − first.
  • Monotonic decreasing — profit = 0.
  • Single day — profit = 0.

Examples

Example 15
{"prices":[7,1,5,3,6,4],"values":[7,1,5,3,6,4]}

Buy day 1 (price 1), sell day 4 (price 6).

Example 20
{"prices":[7,6,4,3,1],"values":[7,6,4,3,1]}

Prices only decline.

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed