Maximum Profit From One Buy and One Sell

Implement maxProfit

Given an array prices where prices[i] is a stock's price on day i, you may buy on one day and sell on a later day to maximize profit. A sale must happen strictly after the purchase. Return the maximum profit achievable, or 0 if no profitable trade exists. This looks like a search over every pair of days, but for any fixed sell day, only ONE earlier day could possibly be the best buy day: whichever one had the lowest price. Tracking that running minimum turns an O(n²) search into a single O(n) pass — and it's really the same Kadane's algorithmKadane's AlgorithmA single pass that, at each position, decides whether to extend the current running result or restart from here — used to find the best contiguous run in an array in O(n). idea in disguise: the day-to-day price differences form an array, and this problem's answer is exactly its maximum-sum contiguous subarray.

Example 1:

Input: prices = [7,1,5,3,6,4]

Output: 5

Example 2:

Input: prices = [7,6,4,3,1]

Output: 0

Example 3:

Input: prices = [1,2]

Output: 1

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

prices =

[7, 1, 5, 3, 6, 4]