Best Time to Buy and Sell Stock - Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Input & Output

Example 1 — Basic Case
$ Input: prices = [7,1,5,3,6,4]
Output: 5
💡 Note: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2 — No Profit
$ Input: prices = [7,6,4,3,1]
Output: 0
💡 Note: In this case, no transactions are done and the max profit = 0. Prices are continuously decreasing, so no profit can be made.
Example 3 — Small Profit
$ Input: prices = [1,2]
Output: 1
💡 Note: Buy on day 1 (price = 1) and sell on day 2 (price = 2), profit = 2-1 = 1.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ prices[i] ≤ 104

Visualization

Tap to expand
Best Time to Buy and Sell StockFind maximum profit from buying and selling stock once715364Day 0Day 1Day 2Day 3Day 4Day 5BUYSELLOptimal TransactionBuy at price 1 (Day 1) → Sell at price 6 (Day 4)Maximum Profit = 6 - 1 = 5Output: 5
Understanding the Visualization
1
Input
Array of stock prices over time
2
Process
Find optimal buy and sell days
3
Output
Maximum profit achievable
Key Takeaway
🎯 Key Insight: Track the minimum price seen so far and calculate profit at each step to find the maximum profit in O(n) time
Asked in
Amazon 89 Microsoft 67 Apple 45 Google 43 Facebook 34
892.3K Views
Very High Frequency
~15 min Avg. Time
19.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen