Funcia
Lv.1arraygreedy

Best Time to Buy and Sell Once

Memory limit
256 MB
Correctness time limit
10000 ms
Acceptance
100.0%
Solvers
1
0

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

pricesresult
[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

  • 1≤1 \le prices.length ≤200,000\le 200{,}000
  • 1≤1 \le prices[i] ≤109\le 10^9

Expected complexity

Time
O(N)
Space
O(1)

Examples

pricesExpected
[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 O(N2)O(N^2) and exceeds the time limit; aim for O(N)O(N).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251038 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance605verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.