Blind 75 · Sliding Window

Best Time to Buy and Sell Stock

Easy

Watch the walkthrough (5:12)

Problem

The array prices holds the price of one stock on each day.
Buy it on one day, and sell it on a later day.
Return the largest profit possible. If no profit is possible, return 0.

Examples

Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5

Example 2:
Input: prices = [7,6,4,3,1]
Output: 0

Constraints

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

Prerequisites

Sliding windows — a left and right edge moving forward only, and the invariant that decides when the left edge advances.
Hash maps or fixed-size counts for what the window currently holds.

How to think about it

1. Track the Cheapest Day So Far Optimal

Intuition

The day to buy is always the cheapest day before the sale. Selling on day i earns today's price minus the cheapest day before it — so only one number from the past matters. Carry the minimum seen so far, and every day answers in constant time. That reframing, from "which pair" to "what do I need from the past", is the whole lesson.

Algorithm

1. Track the lowest price seen so far and the best profit so far.
2. On a day whose price is higher than that lowest price, the profit is today's price minus that lowest price.
3. Keep the better profit; on any other day, today's price becomes the lowest price instead.
4. Never-profitable inputs leave the profit at zero, which is the right answer.

Time & Space

Time O(n) — one pass. Space O(1).