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 1
Input: heights = [2,1,5,6,2,3]
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.
Time Complexity: O(N^3)
Space Complexity: O(1)
Time Complexity: O(N^2)
Space Complexity: O(1)
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
ans = 0
heights.append(0) # dummy tail 0
stack = [] # Store the index of local maximum
for idx in range(len(heights)):
while stack and heights[stack[-1]] >= heights[idx]:
idxOfLocalMax = stack.pop()
width = (idx - stack[-1] - 1) if stack else idx
ans = max(ans, heights[idxOfLocalMax] * width)
stack.append(idx)
return ans
Time Complexity: O(N^2)
Space Complexity: O(N)
https://www.cnblogs.com/grandyang/p/4322653.html
https://medium.com/hoskiss-stand/largest-rectangle-b3a7473320c1