Largest Rectangle in Histogram
Largest Rectangle in Histogram
StackArrayMonotonic Stack
Problem Statement
Given an array of integers heights
representing the histogram's bar height where the width of each bar is 1
, return the area of the largest rectangle in the histogram.
Example
Example 1:
Input Heights:
Largest Area:
10
Solution
A monotonic stack is the key to solving this problem efficiently. The stack will store indices of the histogram bars in increasing order of their heights.
Algorithm Steps
- Initialize a stack to store pairs of [index, height].
- Iterate through the heights. For each bar, while the stack is not empty and the current bar's height is less than the height of the bar at the top of the stack:
- Pop from the stack. Calculate the area with the popped height. The width is the current index minus the index of the new top of the stack.
- Update the max area found so far.
- Push the current bar's [index, height] onto the stack.
- After the loop, process any remaining bars in the stack.
Histogram
Stack [index, height]
Max Area: 0
Start.
Largest Rectangle in Histogram Solution