Largest Rectangle in Histogram
Given bar heights, find the largest rectangle that fits under the histogram.
Open on LeetCode ↗Intuition
The best rectangle using bar i as its height extends to the nearest shorter bar on each side. A monotonic increasing stack finds both boundaries in one pass: when a bar pops, the popper is its right boundary and the new stack top its left.
Approach
Every rectangle is pinned by a bar
The optimal rectangle's height equals some bar's full height — so compute, for each bar, its widest reach.
Pop = settle
Keep indices of increasing heights. When h[i] < top, the top pops: its width is i − (new top) − 1, area = height × width. Settle all taller bars.
Sentinel flush
Append a 0-height bar to force every index to settle by the end. Each bar pushes and pops once → O(n).
Solution & live demo
Edge cases
Nothing settles until the sentinel; widths then span from each bar to the end.
Left boundary is −1 → width is the full prefix, handled by the ternary.