Problem 209835 · easy · Level 02 Linear Data Structures

Best Single Trade

arrays · iteration · best-so-far

You are given prices, where prices[i] is the price of a share on day i. You may buy on one day and sell on a later day, at most once. Return the largest profit you can make. If no profitable trade is possible, return 0.

Examples

Input:  prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 1 (price 1) and sell on day 4 (price 6).

Input:  prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices only fall, so no trade makes money.

Constraints

  • 0 <= len(prices) <= 10**5
  • -10**4 <= prices[i] <= 10**4
  • Target: O(n) time, O(1) extra space.

Goals

  • Track the smallest value seen so far while scanning
  • Update a best answer from the current element and the running minimum
  • Return 0 when no profitable trade exists
Starting Python…