121. Best Time to Buy and Sell Stock
easyGiven daily stock prices, find the maximum profit from a single buy-then-sell transaction. Tests linear-scan thinking and tracking running state, not nested loops.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
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 one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Examples
Example 1
prices = [7,1,5,3,6,4]5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Example 2
prices = [7,6,4,3,1]0Explanation: Prices only decline; no transaction is done so the max profit is 0.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Brute force compares every pair of days — too slow for 10^5 elements.
Hint 2
You only need to know two things as you scan: the lowest price seen so far, and the best profit achievable today.
Hint 3
Track minPrice as you iterate. At each day, candidate profit = prices[i] - minPrice; take the max. Update minPrice if today's price is lower.
Solution approach
Reveal approach
Single pass. Maintain minPrice (the lowest price seen so far) and maxProfit (the best profit found). For each day, the best profit if you sold today is prices[i] - minPrice; update maxProfit if that's larger. Then update minPrice if prices[i] is even lower than the current minimum. Return maxProfit at the end.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- sliding-window
- dynamic-programming
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Meta
- Bloomberg
Practice these live with InterviewChamp.AI
Drill Best Time to Buy and Sell Stock and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →