Best Time to Buy and Sell Stock
Given an array prices where prices[i] is the stock price on day i Find the maximum profit from buying and selling once You must buy before you sell Return 0 if no profit is possible Example: [7,1,5,3,6,4] => 5 (buy at 1, sell at 6)
Best Time to Buy and Sell Stock is the sliding window pattern: grow, shrink, and maintain just enough state to stay linear. It's a great warm-up that builds stateful scanning without a ton of moving parts. The trap is updating window state in the wrong order when you expand or shrink.
Examples
You write
max_profit(prices: List[int])
Example 1
- Input
- prices = [7,1,5,3,6,4]
- returns
- 5
Example 2
- Input
- prices = [7,6,4,3,1]
- returns
- 0
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsSliding Window
I reach for it when
- The question asks for the longest, shortest or best stretch of a sequence.
- A rule like "at most k" or "no repeats" decides what counts as valid.
Say this before you type. Say what makes the window valid, and what you do to the left edge when it breaks.
All 9 Sliding Window problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.