LeetCode/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py
2023-10-02 21:05:36 -07:00

31 lines
1.0 KiB
Python

class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
heights.append(0)
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
heights.pop()
return ans
obj = Solution()
# print(obj.largestRectangleArea([2,1,5,6,2,3])) # 10
# print(obj.largestRectangleArea([2,4])) # 4
# print(obj.largestRectangleArea([0,9])) # 9
# print(obj.largestRectangleArea([0,0,0])) # 0
# print(obj.largestRectangleArea([2,1,2])) # 3
# print(obj.largestRectangleArea([1,2,2])) # 4
# print(obj.largestRectangleArea([0,2,0])) # 2
# print(obj.largestRectangleArea([5,4,1,2])) # 8
# print(obj.largestRectangleArea([2,0,2])) # 2
# print(obj.largestRectangleArea([1,2,3,4,5])) # 9
# print(obj.largestRectangleArea([4,2,0,3,2,5])) # 6