Best Time to Buy and Sell Stock
Track the minimum price so far and maximize profit in one pass.
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
Explanation: Buy on day 2 (price=1), sell on day 5 (price=6). Profit = 6−1 = 5.
Example 2
Explanation: Prices only decrease — no profitable transaction possible.
Constraints
- 1 ≤ prices.length ≤ 10⁵
- 0 ≤ prices[i] ≤ 10⁴
Solutions
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.
Related Concepts
Deepen your understanding with these related topics from our AI Glossary:
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.
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