DSA AnimatorDSA animations
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 & Array
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).

How to solve Best Time to Buy and Sell Stock

LeetCode 121 · Easy · Arrays · Pattern: One Pass

Why the obvious approach is slow

Buying at the lowest price overall does not always work, because the selling day must come after it. And checking every pair of days is O(n²).

The key idea

Walk through the days once, and remember the cheapest price so far. On each day, imagine selling today: the profit is today minus the cheapest so far. Keep the best profit seen.

Remember

Keep the cheapest price so far, and ask what selling today would earn. The order of days matters, so one left to right pass handles it.

Run the animation above on your own input, or watch the 1:20 video explanation of Best Time to Buy and Sell Stock with a dry run and Java code.

More Arrays problems