Back

Best Time to Buy and Sell Stock

easy

You are given an array prices where prices[i] is the price of a given stock on the i-th day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Test Cases

Copy an input into the main harness and Run to verify
Input
prices = [7,1,5,3,6,4]
Expected Output
5

Explanation: Buy on day 1 (price = 1) and sell on day 4 (price = 6), profit = 6 - 1 = 5.

Input
prices = [7,6,4,3,1]
Expected Output
0

Explanation: Prices only fall, so no transaction is done and the max profit is 0.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Hints

Hint 1 — click to reveal

Track the minimum price seen so far as you scan left to right.

Hint 2 — click to reveal

At each day, the best profit ending there is price - minPriceSoFar.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.