easy
Best Time to Buy and Sell Stock
Given daily integer prices, choose at most one buy followed by one sale on a later day. Return the maximum profit, or zero if no profitable transaction exists.
Constraints
- 1 ≤ n ≤ 100000
- 0 ≤ prices[i] ≤ 100000
Examples
in: [[9,2,6,1,5]]
out: 4
Buy before selling
in: [[9,7,3]]
out: 0
Falling prices
Code it yourself
Solve in
Practice journal →Draft saved in this browser.
Public test cases · contract v1
Arguments are passed to your function. Tests are public practice checks, not hidden interview grading. Passing does not prove every possible input.
- Buy before selling
[[9,2,6,1,5]] → 4
- Falling prices
[[9,7,3]] → 0
- Single day
[[6]] → 0
- Best buy after early high
[[8,2,4,10]] → 8
- Equal prices
[[3,3,3]] → 0
Hints:
Which approach applies?
Choose an approach to check your pattern recognition, or reveal the discussion when you need help.