#121EasyGreedy

Best Time to Buy and Sell Stock

Track the minimum price so far and maximize profit in one pass.

AmazonGoogleMicrosoftGoldman SachsBloomberg

Problem Statement

You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize your profit by choosing a single day to buy and a single day to sell in the future. Return the maximum profit, or 0 if no profit is possible.

Examples

Example 1

Input:prices = [7,1,5,3,6,4]
Output:5

Explanation: Buy on day 2 (price=1), sell on day 5 (price=6). Profit = 6−1 = 5.

Example 2

Input:prices = [7,6,4,3,1]
Output:0

Explanation: Prices only decrease — no profitable transaction possible.

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Solutions

1
Brute Force — Try all buy/sell pairs
TimeO(n²)SpaceO(1)

For every pair (i, j) where i < j, compute profit = prices[j] - prices[i] and track the maximum. O(n²) — exceeds time limit for large inputs.

Visual Animation
def maxProfit(prices: list[int]) -> int:
    max_profit = 0
    n = len(prices)
    for i in range(n):
        for j in range(i + 1, n):
            profit = prices[j] - prices[i]
            max_profit = max(max_profit, profit)
    return max_profit

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Greedy to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems