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
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
โ Linear Growth
Space Complexity
O(1)
Only using two variables: min_price and max_profit
โ 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)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code