Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith 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.
Examples
prices = [7,1,5,3,6,4]5prices = [7,6,4,3,1]0Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
š” Hints
Hint 1
Track the minimum price seen so far as you scan left to right.
Hint 2
At each step, calculate the profit if you sold today (current price - min price). Track the maximum profit.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Single pass: track the minimum price seen so far and the maximum profit possible at each position. The sliding window is between the min price day and the current day.
A single pass through the prices array updates the minimum buy price and maximum profit in O(1) per day.
Only a few scalar tracking variables (minPrice, maxProfit) are maintained.
š Real-World Use Cases
Finding the optimal buy-low-sell-high opportunity in historical stock data for backtesting trading strategies.
Analyzing historical price data to determine the best markdown-to-sale timing for maximum revenue per product.
š Dry Run
Initialize minPrice=ā, maxProfit=0. Start scanning at i=0 (price 7)