← Back to DSA Animator
Best Time to Buy and Sell Stock LC #121 Easy Array
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 you can achieve. If no profit is possible, return 0.

Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 1 (price=1) and sell on day 4 (price=6), profit = 6−1 = 5.
Constraints: 1 ≤ prices.length ≤ 10⁵  |  0 ≤ prices[i] ≤ 10⁴
Try Examples
Custom:
Approach
One-Pass Min Scan
Track the minimum price seen so far. At each day, compute profit = price − minPrice. Update maxProfit if larger. No re-scanning needed. O(n) time, O(1) space!
Price Chart
Variables
Day i
Price
Min Price
Max Profit
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
minPrice = ∞, maxProfit = 0
2
For each price: check if new minimum
3
Else: profit = price - minPrice
4
maxProfit = max(maxProfit, profit)
Time
O(n)
Space
O(1)
Why It Works

For any selling day i, the optimal buy day is the minimum price in [0..i-1]. We track the running minimum — no re-scan needed. At each step, profit = todayPrice − lowestSeen. If this beats maxProfit, update it. A decreasing sequence yields profit 0 (we never sell below buy).