Arrays · Coding problem
Best Time to Buy and Sell Stock
A free coding problem from the Single-Pass State Tracking skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
prices[i] is a share's price on day i. You may buy once and sell once on a later day, or not trade at all. Return the biggest profit you can lock in, or 0 if no trade makes money.
Example
Input: prices = [9, 11, 4, 7, 3, 8, 6]
Output: 5
Buy at 3 and sell at 8 the next day. Selling at 11 after buying at 9 makes only 2.
Solve it in a single O(n) pass with O(1) extra space.
Constraints
1 <= prices.length <= 4 * 10^50 <= prices[i] <= 10^4
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Single-Pass State Tracking
Solve it Best Time to Buy and Sell Stock free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime