Best Time to Buy and Sell Stock
An easy Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 25 roles
- Platform
- LeetCode
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 = [7,1,5,3,6,4]
- Output
- 5
- Why
- Buying on day 2 at price 1 and selling on day 5 at price 6 yields a profit of 6 - 1 = 5.
Example 2
- Input
- prices = [7,6,4,3,1]
- Output
- 0
- Why
- Prices decline every day, so no profitable transaction can be executed.
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-09Every 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.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .