Best Time to Buy and Sell Stock
Maximum profit from one buy followed by one later sell.
Problem
You are given an array prices where prices[i] is the price of a stock on day i. Choose one day to buy and a later day to sell to maximize profit. Return the maximum profit, or 0 if no profit is possible.
- You must buy before you sell.
- Only one transaction is allowed.
- If no profit is possible, return 0.
Examples
Approach
- Ask of each day: "if I sell today, what is the best day I could have bought?" - the cheapest price seen so far.
- Start with minPrice = prices[0] and best = 0.
- For each later day, lower minPrice if today is cheaper, then compute price - minPrice and keep the best.
- The window is [day of minPrice, today]; it slides forward whenever a new low appears.
Brute force: Check every buy day against every sell day - a loop inside a loop.
Common mistakes
- Tracking the global minimum and maximum separately ignores order - the maximum may come before the minimum.
- Starting best at -Infinity instead of 0 returns a loss when prices only fall.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned