Greedy Algorithms
Easy
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.
10 min read
Solve on LeetCodeProblem 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
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Complexity Analysis
- Solution
- Complexity Analysis
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.
