Largest Rectangle in Histogram
ID: 122; hard
Last updated
ID: 122; hard
Last updated
We used a non-decreasing stack in this solution. Each time before we push the element into the stack, we pop out the elements that are larger than it. Then, each time when the element is popped from the stack, we know the first element to its left that is smaller than it (top of the stack) and the first element to its right that is smaller than it (element to be pushed). So, we can calculate the area squeezed by these two elements, which is h * w
. This is the maximum area reached by stretching the element to be popped to its left and right (restrained by elements that are smaller than it to its left and right).
Because we need to calculate the width (w
), instead of pushing the actual elements, we push the indices to the stack.