LeetCode Visualizations

← Back to Home

Best Time to Buy and Sell Stock

An Interactive Visual Explainer

Idea By: Chetan Pachpande | Executed By: Gemini

Problem Description

You are given an array prices where prices[i] is the price of a given stock on the i-th 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.

Complexity Analysis

Time Complexity: O(N)

We iterate through the prices array only once.

Space Complexity: O(1)

We only use a few variables to store the minimum price and maximum profit, regardless of the input size.

Intuition

The goal is to find the largest difference between two numbers in an array, with the constraint that the smaller number (buy price) must appear before the larger number (sell price).

A brute-force approach would be to check every possible pair of buy and sell days, but that would be too slow (O(N²)).

A much more efficient approach is to iterate through the prices just once. While we iterate, we maintain two key pieces of information:

  1. The lowest stock price seen so far (min_price). This is the best day we could have possibly bought the stock up to the current day.
  2. The maximum profit seen so far (max_profit). This is the best profit we could have made.

For each day, we calculate the potential profit if we were to sell on that day: `current_price - min_price`. We then update our `max_profit` if this new profit is higher. Finally, we update `min_price` if the current day's price is a new low. This ensures we always know the best buying price for any future selling day.

Step-by-Step Code

Live Visualization & Controls

Min Price Seen: 0
Max Profit Found: 0
Current Price: 0
Potential Profit: 0

Execution Controls