All coding questions

Best Time to Buy and Sell Stock

easy
Blind 75NeetCode 150arrayssliding-windowgreedy

Problem

Given daily prices of a stock, find the maximum profit from a single buy followed by a later sell. If no profitable transaction exists, the profit is zero.

Examples

Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Buy at 1, sell at 6.
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Prices only fall, so no profit.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
Hints(tap to reveal)
  • 1. Track the lowest price seen so far.
  • 2. Profit at each day is today's price minus that minimum.
Optimal approach(spoiler)
  1. Walk the prices left to right, tracking the minimum price so far.
  2. At each day compute profit if selling today after buying at that minimum.
  3. Keep the best profit seen.
  4. Never let profit drop below zero.
  5. O(n) time, O(1) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor