-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12_largest_rectangle_area.py
42 lines (32 loc) · 1.16 KB
/
12_largest_rectangle_area.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution(object):
def largestRectangleArea(self, heights):
n = len(heights)
def findPreviousSmaller():
result = [-1] * n
stack = []
for index in range(n):
while stack and heights[stack[-1]] >= heights[index]:
stack.pop()
if stack:
result[index] = stack[-1]
stack.append(index)
return result
def findNextSmaller():
result = [n] * n
stack = []
for index in range(n - 1, -1, -1):
while stack and heights[stack[-1]] >= heights[index]:
stack.pop()
if stack:
result[index] = stack[-1]
stack.append(index)
return result
result = 0
leftSmaller = findPreviousSmaller()
rightSmaller = findNextSmaller()
for index in range(n):
height = heights[index]
breadth = rightSmaller[index] - leftSmaller[index] - 1
currArea = height * breadth
result = max(result, currArea)
return result