Best Time to Buy and Sell Stock
Maximize profit by choosing a single day to buy and a different day in the future to sell.
Problem Understanding
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. If no profit possible, return 0.
Strategy
We can iterate through the prices and keep track of:
- Min Price So Far: The lowest price we've seen to buy at.
- Max Profit: The best profit we could get if we sold today (
Current Price - Min Price).
Initialize
min_price = infinity,max_profit = 0.For each price
p:Update
min_price = min(min_price, p)Update
max_profit = max(max_profit, p - min_price)
Interactive Visualization
Initializing...
Watch how we track the minimum price seen so far to calculate maximum potential profit at each day.
- Problem Understanding
- Strategy
- Interactive Visualization
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
