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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code