Zero To DSAZero To DSA
Privacy Policy
Two Sum (Brute Force)Product of Array Except Self

Best Time to Buy and Sell Stock

easy
Time: O(n)
Space: O(1)

You are given an array `prices` where `prices[i]` is the price of a given stock on day i. You want to maximize your profit by choosing a single day to buy and a different day to sell. Return the maximum profit. If no profit is possible, return 0.

Constraints

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

Examples

Input: prices = [7,1,5,3,6,4]
Output: 5
Buy at 1 (day 2), sell at 6 (day 5). Profit = 5.
Input: prices = [7,6,4,3,1]
Output: 0
No profit possible, return 0.