Best Time to Buy and Sell Stock

Easy

Topics
ArrayDynamic Programming

You are given an array prices where prices[i] is the price of a stock on day i. Maximize profit by choosing one day to buy and a later day to sell. Return the max profit, or 0 if none.

Example 1

715364
buy, then sell
Buy at 1 (day 1) and sell at 6 (day 4) for 5.
Bars are the daily prices, left to right.
Input:  prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy at 1, sell at 6.

Example 2

76431
Prices never rise after a cheaper day, so no profitable trade exists and the answer is 0.
Input:  prices = [7,6,4,3,1]
Output: 0

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

You must buy before you sell, so for each day the best profit is that day’s price minus the cheapest price on any earlier day.

Sweeping left to right, keep the minimum price seen so far behind you and, at each day, ask "what if I sold today?"

Approach

  1. Track minPrice (cheapest seen so far) and best profit.
  2. For each price, update best = max(best, price - minPrice).
  3. Then update minPrice = min(minPrice, price).
  4. Return best (0 if prices only fall).

Walkthrough

prices = [7, 1, 5, 3, 6, 4]
day 7: min=7 best=0
day 1: min=1 best=0
day 5: best=4  min=1
day 3: best=4
day 6: best=5  (6-1)
day 4: best=5  -> answer 5

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two scalars.

Common Pitfalls

  • Update best before minPrice each day, otherwise you allow buying and selling on the same day for 0 which is harmless, but the order keeps the logic clear.

Full Solution — all languages

class Solution:
    def maxProfit(self, nums):
        best = 0
        cheapest = float('inf')
        for price in nums:
            if price < cheapest:
                cheapest = price
            elif price - cheapest > best:
                best = price - cheapest
        return best
SensAI
Beta
Tap the mic to stop voice mode