Best Time to Buy and Sell Stock

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Best Time to Buy and Sell Stock

Approach

Scan prices left to right, tracking the minimum price seen so far. At each day, calculate the profit if selling at the current price. Update the maximum profit whenever a better profit is found. The minimum price resets whenever a new low is encountered.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Running Minimum

Why It Works

The optimal buy day is always the lowest price before the sell day. By tracking the running minimum, each potential sell day is compared against the best possible buy price.

Updated Feb 2026