Best Time to Buy and Sell Stock - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an array of prices, compute the maximum possible profit from a single buy → sell transaction.

Key Idea (Intuition)

You must buy before you sell. For any day treated as the sell day, the best buy is simply the lowest price seen so far. So we maintain two running values while scanning once: minPrice (lowest price up to the current day) and maxProfit (best profit found so far). At each day, we (1) compute today’s possible profit against minPrice and update maxProfit, then (2) update minPrice with today’s price.

Initialization

  • maxProfit = 0 — best profit found so far.
  • minPrice = Infinity — the minimum price seen so far; first price will become the initial minimum.

Traversal

Iterate over the array prices from left to right (one pass). For each price:

Per-Iteration Logic

  1. Compute possible profit at this sell point:
    possibleProfit = price − minPrice
    Treat today as the sell day; compare with the lowest buy price seen so far.
  2. Update maxProfit:
    maxProfit = Math.max(maxProfit, possibleProfit)
    Keep the best profit encountered so far.
  3. Update minPrice:
    minPrice = Math.min(minPrice, price)
    Refresh the lowest-so-far price for future sell-day checks.

Return

After the loop finishes, return maxProfit.

Why This Works

A single pass is enough because for each day we only need the minimum price from previous days. By maintaining minPrice, we can directly calculate the best possible profit if we sell at today’s price. By maintaining maxProfit alongside, we always keep track of the best profit across all days.

Time Complexity

The algorithm makes a single pass over the input array of prices. Each iteration performs constant-time operations such as comparisons and assignments. Thus, the overall time complexity is O(n), where n is the number of prices.

Space Complexity

The algorithm uses only a constant amount of extra space for variables such as maxProfit, minPrice. At each iteration, the same fixed variables are updated, and no new structures are created. No additional data structures are required that grow with the input size. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Best Time to Buy and Sell Stock coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/best-time-to-buy-and-sell-stock.