Best Time to Buy and Sell Stock
An easy Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 26 roles
The problem
Given an array of daily stock prices, find the maximum profit obtainable from choosing a single day to buy and a later day to sell.
Example 1
- Input
- prices = [8,2,6,1,5,9]
- Output
- 8
- Why
- Buy on day 4 at price 1 and sell on day 6 at price 9 for 9 - 1 = 8. Buying earlier at 2 and selling at 9 would give 7, which is less.
Example 2
- Input
- prices = [9,8,5,4,2]
- Output
- 0
- Why
- The price only falls, so every sale would lose money; the best choice is not to trade.
Example 3
- Input
- prices = [2,4,1]
- Output
- 2
- Why
- Buying at 2 and selling at 4 yields profit 2; buying at 1 has no subsequent higher selling day.
Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
How to think about it
Updated 2026-09-29Every potential selling day can only achieve its best profit against the lowest purchase price seen before it. Walking forward while maintaining that running minimum converts the problem from comparing all pairs into evaluating a single subtraction at each day. The highest subtraction encountered across the entire sequence is the answer.
Approaches, worst first
Brute force pair evaluation
time O(n^2) · space O(1)
Compare every buy day i against every subsequent sell day j > i and compute prices[j] - prices[i]. Evaluates all forward combinations, but repeats work across identical price drops and runs in quadratic time.
Running minimum trackingWrite this one
time O(n) · space O(1)
Initialize minPrice to prices[0] and maxProfit to 0. For every subsequent price, update maxProfit with max(maxProfit, price - minPrice) and then update minPrice with min(minPrice, price). Captures the optimal transaction in one linear sweep.
Where people lose marks · 3
- Updating the minimum price before calculating the potential profit on the same day, which allows buying and selling simultaneously for 0 profit on a crash day.
- Returning a negative profit when prices strictly decrease instead of clamping the result to 0.
- Picking the global minimum price after it occurs past the global maximum price, which violates the chronological requirement that buying precedes selling.
Full solution
Running-minimum tracking: at each day, price minus the lowest price seen so far is the best profit ending that day. One linear sweep, O(n) time and O(1) space, versus the O(n^2) brute-force pair check.
Python
def max_profit(prices: list[int]) -> int:
min_price = prices[0]
max_profit_so_far = 0
for price in prices[1:]:
# compute profit before updating the minimum, else buy/sell same day
max_profit_so_far = max(max_profit_so_far, price - min_price)
min_price = min(min_price, price)
return max_profit_so_far
JavaScript
function maxProfit(prices) {
let minPrice = prices[0];
let maxProfitSoFar = 0;
for (let i = 1; i < prices.length; i++) {
const price = prices[i];
maxProfitSoFar = Math.max(maxProfitSoFar, price - minPrice);
minPrice = Math.min(minPrice, price);
}
return maxProfitSoFar;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
More Arrays problems
Target Roles
Core requirement for 26 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .