Largest rectangle in histogram
- CH1 i
Bars wait in rising order. A lower bar closes each taller one, whose rectangle reaches back to the bar under it.
Step through it →A monotonic stack holds the items still waiting for an answer, in sorted order, and each new item pops every item it answers.
Before a day is pushed, it pops every colder day on top, so it always lands on one at least as warm. Each day is pushed once and popped at most once, so the scan is O(n).
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Only a warmer day pops. Popping on ties would give the first three days a wait of 1, not 0.
Bars wait in rising order. A lower bar closes each taller one, whose rectangle reaches back to the bar under it.
Step through it →mins is a monotonic stack too: each entry is the smallest at or below its height.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def daily_temperatures(temperatures): answer = [0] * len(temperatures) stack = [] # days still waiting for a warmer one for i, t in enumerate(temperatures): while stack and temperatures[stack[-1]] < t: j = stack.pop() answer[j] = i - j stack.append(i) return answer