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
01
15
23
36
44
51/8
Narrationstep 1 of 8
Track the cheapest price seen so far. For each day, best profit = today's price − cheapest so far.
Variables
minSoFar=∞
best=0
How to think about it
- Brute force (every buy/sell pair) is O(n²).
- You never need to look backward — the only buy day worth remembering is the cheapest so far.
- Walk once; keep two scalars (minSoFar, best).
- 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 1
5{"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 2
0{"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