LeetCode/NeetCodeRoadmap/Stack/84_Largest_Rectangle_in_Histogram.py
2023-10-02 19:15:11 -07:00

40 lines
1.3 KiB
Python

class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
rect = []
h = len(heights)
if len(heights) <= 2:
if len(heights) == 1:
return heights[0]
else:
if heights[0] == 0 or heights[1] == 0:
return max(heights[0], heights[1])
low = min(heights[0], heights[1])
return low*2
for x in range(h):
count = 1
for y in range(x+1, h):
if heights[x] == min(heights):
rect.append(heights[x]*len(heights))
elif heights[x] > heights[y]:
# print(f'{heights[x]} * {count} = {heights[x]*count}')
rect.append(heights[x]*count)
else:
count += 1
if rect:
return max(rect)
else:
return 0
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