Best Time to Buy and Sell Stock - Problem

You're given an array prices where prices[i] represents the price of a stock on the i-th day. Your goal is to maximize profit by choosing a single day to buy one share of stock and a different day in the future to sell that stock.

The key constraint is that you must buy before you sell - you can't sell a stock you don't own! Return the maximum profit you can achieve from this transaction. If no profit is possible, return 0.

Example: If prices = [7,1,5,3,6,4], you should buy on day 2 (price = 1) and sell on day 5 (price = 6) for a profit of 5.

Input & Output

example_1.py โ€” Standard 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.py โ€” No Profit Case
$ Input: prices = [7,6,4,3,1]
โ€บ Output: 0
๐Ÿ’ก Note: In this case, no transactions are done and the max profit = 0. The prices are continuously decreasing, so any purchase would result in a loss.
example_3.py โ€” Single Element
$ Input: prices = [1]
โ€บ Output: 0
๐Ÿ’ก Note: Cannot complete any transaction with only one price point, so return 0.

Visualization

Tap to expand
Stock Trading VisualizationBuy (Valley)Sell (Peak)Maximum ProfitAlgorithm TrackingMin Price: 7 โ†’ 1 (found better valley)Max Profit: 0 โ†’ 4 โ†’ 5 (found better peak)Current: profit = 6 - 1 = 5Status: โœ“ Optimal solution foundKey InsightLowest price = Best buy pointCalculate profit at each dayTrack maximum profit๐ŸŽฏ Key Insight: We only need the minimum price seen so far - any future sell decision should use the cheapest available buy price
Understanding the Visualization
1
Track the Valley
Keep track of the lowest point (price) we've seen so far - this is our best buying opportunity
2
Calculate Peak Profit
At each new point, calculate how much profit we'd make if this were our selling point
3
Update Records
Update our maximum profit if current profit is better, and update minimum price if current price is lower
4
Single Pass Success
By the end of our journey, we've found the optimal valley-to-peak combination
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking all combinations, track the minimum price (best buy point) and calculate profit for each potential sell day in a single pass

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, each element visited once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two variables: min_price and max_profit

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค prices.length โ‰ค 105
  • 0 โ‰ค prices[i] โ‰ค 104
  • You must buy before you sell (cannot sell on the same day or before buying)
Asked in
Amazon 47 Google 42 Meta 38 Microsoft 35 Apple 28
73.9K Views
Very High Frequency
~15 min Avg. Time
1.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