Best Time to Buy & Sell Stock
Module 4 · Arrays & Dynamic Arrays
Problem
prices[i] is a stock's price on day i. Choose one day to buy and a
later day to sell to maximize profit. Return the maximum profit, or 0
if no profitable trade exists.
Examples
Example 1
Input
prices = [7,1,5,3,6,4]Output5Explanation. buy at 1 on day 1, sell at 6 on day 4
Example 2
Input
prices = [7,6,4,3,1]Output0Explanation. prices only fall — don't trade
Constraints
1 ≤ n ≤ 10⁵ · 0 ≤ price ≤ 10⁴.
Attempt it first
This one isn't a write-pointer problem — it's here to teach a different single-pass discipline. The constraint n ≤ 10⁵ rules out one obvious approach (you know which, and you know why — you read constraints now).