2. Best Time to Buy and Sell Stock

Easy · Array

You are given an array of integers representing stock prices on consecutive days. You must find the maximum profit you can make by buying on one day and selling on a later day. If no profit is possible (prices only decrease), return 0. The input is an array of prices, and you should return a single integer representing the maximum profit.

Examples

Example 1
Input: [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy at 1, sell at 6 → profit 5
Example 2
Input: [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices only fall — no profitable trade

Constraints