Problem
Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
1 |
|
Explanation 1
-
Iterate each element, if the next element is less than the current element or we hit the end of the array, then we start to find the rectangle’s area and that rectangle’s right side is fixed on current index.
-
We can find the min height by loop backward from the current index to zero, and we multiple the width with the minHeight.
Solution 1
1 |
|
Explanation 2
-
We can find the area by finding the current element’s leftMost and rightMost index and
area = heights[cur] * (rightMost-leftMost-1)
. From the above example, if the current element is at index 2, its height is 5. Then theleftMost
is at index 1, andrightMost
is at index 4 (leftMost is the previous first index element height that is less than the current element height, rightMost is the next first index element height that is less than the current element height). So, when current index is 2, its maximum area is5 * (4-1-1) = 10
which shows the red area. Another example is when current index is 3 which is at height 6, its maximum area is6 * (4-2-1) = 6
. -
We can create a ascending stack to hold the ascending height’s element index. Iterating each element, when the curent element height is greater than the stack’s top height, then we push it to the stack. Else, we set the current element’s index to be the
rightMost
, we pop the top index of the stack and let it beind
,leftMost
will now be the peek of the stack, then we use the above method to calculate themax
area. The current index needs to stay the same and we need to compare it with the top of the stack to determine if we need to push it to the stack or not. If not, then we pop find out therightMost
andleftMost
and calcualte the area again. -
After we finish iterating, if the stack is not empty, then we set the
rightMost
to the stack’s top index plus one.ind
is the pop element of the stack,leftMost
is the peek element of the stack or -1 if stack is empty. We calcualte themax
area again until the stack is empty.
Solution 2
1 |
|