Best Time to Buy and Sell Stock

Given an array prices where prices[i] is the stock price on day i, choose a single day to buy and a later day to sell. Return the maximum profit, or 0 if no…

Given an array `prices` where `prices[i]` is the stock price on day `i`, choose a single day to buy and a later day to sell. Return the maximum profit, or `0` if no profit is possible.

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

Example 1: input prices = [7, 1, 5, 3, 6, 4]; output 5. Buy on day 1 (price = 1) and sell on day 4 (price = 6). Profit = 6 - 1 = 5.

Example 2: input prices = [7, 6, 4, 3, 1]; output 0. Prices fall every day. No profitable transaction is possible.

Category: Arrays. Topic: arrays. Difficulty: Easy. Patterns: linear-scan, greedy.