<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg" style="width: 522px; height: 242px;" />
<pre>
<strong>Input:</strong> heights = [2,1,5,6,2,3]
<strong>Output:</strong> 10
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg" style="width: 202px; height: 362px;" />
<pre>
<strong>Input:</strong> heights = [2,4]
<strong>Output:</strong> 4
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        if not heights:
            return 0
        stack = [] # maintains the index, an strictly increasing stack
        maxArea = 0
        for i in range(len(heights)+1): # last height is 0;
            curH = 0 if i == len(heights) else heights[i] # current height at location i; 
            # last one is 0 for cases like [1,2,3] so that we have a chance to pop all in the stack

            while stack and curH <= heights[stack[-1]]: # we saw a smaller height, time to pop and calculate area; Need to use <=, because it is a strictly increasing stack (we need to find the strictly smaller element on the left;) so that when we quit, we can append.
                h = heights[stack.pop()]
                start = stack[-1] if stack else -1 # if stack is empty, start = -1 (for cases like [1])
                # start location, index of the first smaller height in the left of the poped height; 
                # i is the first samller height in the right of the poped height
                # |__________|........|___________________|___________|
                #  stack[-1]              stack.pop()           i
                width = i - start - 1
                # print(["stack containing index", stack, "curH", curH, "i", i, "start", start, "width", width, "h", h, "area", width*h])
                maxArea = max(maxArea, width * h)

            # currH > heights[stack[-1]]
            # print(stack)
            stack.append(i) # curH is higher then top of stack or stack is empty, push to increasing stack

        return maxArea
30100