DSA Visualizer · 25 visualizationsBest Time to Buy and Sell Stock
Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.
Start on day 0 at price 7. The cheapest price so far is 7, so there is no profit yet.
Problem
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.
Examples
Buy on day 2 (price=1), sell on day 5 (price=6)
Prices only decrease, no profit possible
Constraints
- 1 ≤ prices.length ≤ 10⁵
- 0 ≤ prices[i] ≤ 10⁴
Intuition
The best day to sell is any day, and the best day to buy is the cheapest day before it. So sweep left to right keeping the minimum price seen so far; the best profit ending today is today's price minus that minimum.
Brute force → Optimal
Try every buy day and every later sell day, and keep the largest profit.
One pass. Track the minimum price so far; at each day compute price − min and keep the best.
Complexity
Edge cases
- Fewer than two days: there is no future day to sell, so the answer is 0.
- Prices that only fall, e.g. [7,6,4,3,1]: there is no profitable pair, so return 0.
Common mistakes
- Buying and selling on the same day, which is not allowed — the sell day must come after the buy day.
- Updating the minimum before computing today's profit, which would let a day pair with itself.