Best Time to Buy and Sell Stock
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
prices[i] is the price of a stock on day i. You may buy once and then sell once on a later day.
Return the maximum profit you can make. If no trade makes money, return 0.
Understand the problem
- Profit = sell price − buy price.
- You must buy before you sell. You can't sell on day 2 and buy on day 5.
- You make at most one trade (one buy, one sell). You may also choose not to trade at all, which gives a profit of
0.
Example 1
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5Buy on day 1 (price 1), sell on day 4 (price 6): 6 - 1 = 5. Buying at 1 and selling at 7 would be better, but 7 is on day 0, before the purchase, so it's not allowed.
Example 2
Input: prices = [7, 6, 4, 3, 1]
Output: 0The price only goes down. Every trade loses money, so the best choice is not to trade.
Example 3
Input: prices = [2, 4, 1]
Output: 2Buy at 2, sell at 4. The lowest price, 1, comes last, so there's no later day to sell it on.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk through the days once, remembering the cheapest price so far, and on each day check how much you'd make by selling today.
The naive approach (and why it's slow)
Try every pair of days (buy on i, sell on a later j) and keep the best profit. That's about n × n / 2 pairs, O(n²). For 100,000 days, 5 billion pairs.
The key insight
Flip the question around. Instead of "which pair is best?", ask for each day: "if I sell today, what's the most I could make?"
The answer: today's price minus the cheapest price on any earlier day. And we don't need to search for that cheapest price each time. We just keep a running minimum as we walk forward, which costs one comparison per day.
This is the simplest form of a sliding window: the window stretches from the cheapest day to today, and its left edge jumps forward whenever we find a new lowest price.
Step by step
prices = [7, 1, 5, 3, 6, 4]:
| Day | Price | Profit if I sell today (price - minPrice) | Best profit | minPrice afterwards |
|---|---|---|---|---|
| 0 | 7 | 7 - ∞ (nothing to buy yet) | 0 | 7 |
| 1 | 1 | 1 - 7 = -6 | 0 | 1 (new low) |
| 2 | 5 | 5 - 1 = 4 | 4 | 1 |
| 3 | 3 | 3 - 1 = 2 | 4 | 1 |
| 4 | 6 | 6 - 1 = 5 | 5 | 1 |
| 5 | 4 | 4 - 1 = 3 | 5 | 1 |
Answer: 5.
Notice the order inside each day: we check "sell today" before updating the minimum. That's what guarantees we always buy on an earlier day than we sell.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One pass, constant work per day.
- Memory: O(1). Just two numbers.
Common mistakes
- Using the global minimum and maximum. In
[7, 1, 5, 3, 6, 4]the max is7and the min is1, but7comes first, so7 - 1isn't a real trade. - Updating
minPricebefore computing the profit. It still works here (it just computes a profit of0for that day), but thinking "sell first, then maybe buy" keeps the logic honest in harder variants. - Returning a negative number when prices only fall. Starting
bestat0means "don't trade" is always an option.
Going deeper
There's a whole family of these problems: unlimited trades, at most two trades, a cooldown day, a fee per trade. They're usually solved with dynamic programming, tracking your best money in each state ("holding a stock" vs "not holding"). This problem is the simplest member of that family.
Reference solution
/**
* @param {number[]} prices
* @return {number}
*/
export default function maxProfit(prices) {
let minPrice = Infinity // cheapest price seen so far (best day to have bought)
let best = 0 // best profit so far; 0 means "don't trade"
for (const price of prices) {
// Sell today: buy at the cheapest EARLIER price. Check this first...
best = Math.max(best, price - minPrice)
// ...then maybe today is the new cheapest day to buy for a later sale.
minPrice = Math.min(minPrice, price)
}
return best
}export default function maxProfit(prices: number[]): number {
let minPrice = Infinity // cheapest price seen so far (best day to have bought)
let best = 0 // best profit so far; 0 means "don't trade"
for (const price of prices) {
// Sell today: buy at the cheapest EARLIER price. Check this first...
best = Math.max(best, price - minPrice)
// ...then maybe today is the new cheapest day to buy for a later sale.
minPrice = Math.min(minPrice, price)
}
return best
}def max_profit(prices: list[int]) -> int:
min_price = float("inf") # cheapest price seen so far (best day to have bought)
best = 0 # best profit so far; 0 means "don't trade"
for price in prices:
# Sell today: buy at the cheapest EARLIER price. Check this first...
best = max(best, price - min_price)
# ...then maybe today is the new cheapest day to buy for a later sale.
min_price = min(min_price, price)
return best