Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Dynamic Programming High frequency Solution Available Practice Mode

Best Time to Buy and Sell Stock LeetCode Solution

Tags: #Array #Dynamic Programming

Approach Summary

Track running minimum price. At each day, profit = price - min_so_far. Track max profit seen.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Dynamic Programming Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Dynamic Programming pattern.

Framework: Dynamic Programming • Interview Prep: Tested at FAANG • Explore all Dynamic Programming problems & invariants →

How to Recognize This Pattern

  • Single buy and sell, maximize profit
  • Track min seen so far — greedy O(n)

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Dynamic Programming

Frequently Asked Questions

What is the optimal time and space complexity for Best Time to Buy and Sell Stock?
The optimal solution for Best Time to Buy and Sell Stock achieves O(n) runtime complexity and requires O(1) auxiliary space. We scan the prices array once in linear O(n) time with simple min and max calculations per day. Auxiliary space is strictly O(1) as only two primitive integer variables are tracked.
How do I identify that Best Time to Buy and Sell Stock requires the Dynamic Programming pattern?
In technical interviews, look for key problem signals: Single buy and sell, maximize profit; Track min seen so far — greedy O(n). Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Dynamic Programming strategy.
What critical edge cases must be handled in Best Time to Buy and Sell Stock?
Essential edge cases to verify include: Strictly decreasing prices (e.g. [7, 6, 4, 3, 1]) where no profit is possible (returns 0); Array of length 1 (returns 0); Maximum price appears before the minimum price; All prices identical. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Best Time to Buy and Sell Stock?
Best Time to Buy and Sell Stock is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Facebook, Microsoft, Google, Apple.
Buy me a coffee
Daily Practice
0/0