Example 1
- Input
- heights = [2,1,5,6,2,3]
- Output
- 10
The bars of height 5 and 6 form a 5 by 2 rectangle of area 10, which beats every other span.
Given the bar heights of a histogram where each bar is one unit wide, find the area of the largest rectangle that fits under consecutive bars. A nondecreasing stack reuses span boundaries to find the answer in linear time.
Given an array of integers heights representing the histogram bar heights where the width of each bar is 1, return the area of the largest rectangle in the histogram.
For a bar of height h, the tallest rectangle using that height stretches left and right until a shorter bar blocks it, so its area is h times that span width. The answer is the maximum of this value over every bar.
1 <= heights.length <= 10^50 <= heights[i] <= 10^4The bars of height 5 and 6 form a 5 by 2 rectangle of area 10, which beats every other span.
The single bar of height 4 gives area 4, which is the largest achievable.
There is one bar but its height is zero, so every rectangle has area zero. This checks both the minimum length and a zero height.
Equal heights can share one rectangle: height 2 across all three bars gives area 6. Treating equality as a blocking shorter bar would miss this width.
The zero splits the two positive bars. Any rectangle crossing it has height zero; either single height-2 bar gives the best area 2.
A rectangle must cover consecutive bars, and its height cannot exceed the shortest bar it covers. In [2,1,5,6,2,3], bars at indices 2 and 3 have heights 5 and 6, so together they support height 5, width 2, and area 10. Extending that rectangle to index 4 lowers its allowed height to 2. Instead of repeatedly searching for these stopping points, a monotonic stack stores unfinished spans in nondecreasing height order: taller spans end when a shorter bar arrives.
Reveal Expand Every Bar: intuition, complexity, and code
0 contribute no area and force every taller bar on the stack to close.[2,2,2] returns 6; this code keeps duplicates until a smaller bar or the final flush.[2,0,2] returns 2, while [0,0,0] returns 0.1000000000; use the linear approach to handle that size.i - index in the stack approach includes the shorter bar that just ended the span. In the expansion approach, use right - left - 1 because both stop pointers are excluded.>: duplicates stay, so the invariant is nondecreasing heights.A monotonic stack turns nearest-smaller queries into a single pass: rising values wait on the stack and each arrival settles every taller value before it.