Lv.1arraygreedy
Best Time to Buy and Sell Once
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Acceptance
- 100.0%
- Solvers
- 1
You are given an array prices where prices[i] is the price of a stock on day i.
You may buy once and sell once on a later day. Return the maximum profit you can make, or 0 if no trade is profitable.
Examples
| prices | result |
|---|---|
[7, 1, 5, 3, 6, 4] | 5 |
[7, 6, 4, 3, 1] | 0 |
[3] | 0 |
Example 1 — buy on day 2 (price 1) and sell on day 5 (price 6).
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(prices: int[]) → int
Constraints
-
prices.length -
prices[i]
Expected complexity
- Time
- O(N)
- Space
- O(1)
Examples
| prices | Expected |
|---|---|
[7,1,5,3,6,4] | 5 |
[7,6,4,3,1] | 0 |
[3] | 0 |
Hint
Hint
Fix the selling day j: the best buying day is the cheapest day before j. Sweep once, keeping the minimum price seen so far
and the best prices[j] - min. Checking every pair is and exceeds the time limit; aim for .
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1038 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 5 | verdict only |