Given an array of integers


Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Constraints:
1 <= heights.length <= 105 0 <= heights[i] <= 104
Contents
Solution 1 - Using a Stack
When finding area of largest rectangle based on heights in the
-
If a smaller height comes after bigger height: For example if the heights are
[2,1,3] In this case, area that can be drawn from the first height 2, will be reduced to height 1 if it need to be included with next height which is 1.
-
If a bigger height comes after smaller height: For example if the heights are
[2,3] In this case, area that can be drawn to the second height 3, we can include the smaller heights prior to that as well.
In this approach, we are going to use a
Let's look at an example,
-
First, we will add 1st height 1 to the stack,
stack = [(0, 2)] andmaxArea = 0 . -
Next, 2nd height is
1 , which is smaller than the previous height, so we pop the previous element from stack and updatemaxArea = (height * width) = 2 * 1 = 2 and stack becomesstack = [(0, 1)] , index will still be 0 because we can still use 1 unit of height from the previous height 2, when we have to compute area at a later height, this will help to get the width (from which index, we can consider the height). -
Next, 3rd element is
3 , since this is bigger height than the previous height in stack, we will add it to stackstack = [(0, 1), (2, 3)] andmaxArea = 2 -
Next, 4th height is
1 , which is smaller than the previous height, so we pop the previous element from stack and updatemaxArea = (height * width (current index - previous element index)) = 3 * (3-2) = 3 and stack becomesstack = [(0, 1), [2, 1]] , index will be 2 because we can still use 1 unit of height from the previous height 3. -
Now, let's look at the elements in
stack and compute the area possible at those indexes, by taking theheight from the stack and for thewidth takeheights.length - index this will give how many unit heights can be considered with that height.-
Area for the first element will be =
1 (height) * 4 = 4 ( heights array length - index = 4 - 0, that is 1 unit height can be considered from all heights). -
Area for the second element will be =
1 (height) * 3 = 3
-
Area for the first element will be =
-
So the max area will be
4 .
Complexity Analysis:
Time complexity: Time complexity for the solution will be O(n) where
Space complexity: O(n) for storing elements into stack.
Above implementations source code can be found at