The Core Insight
For any bar, the largest rectangle that fully includes it is limited by the first strictly smaller bar to its left, and the first strictly smaller bar to its right.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an array of integer heights representing a histogram, find the area of the largest bounding rectangle.
For any bar, the largest rectangle that fully includes it is limited by the first strictly smaller bar to its left, and the first strictly smaller bar to its right.
We use a stack to keep track of bars in strictly increasing height order. When we see a smaller bar, it acts as the "right boundary" for the taller bars currently sitting on top of the stack.
When popping a bar, its height `h` is known. Its right boundary is the current index `i`. Its left boundary is the index of whatever remains at the top of the stack after it's popped!