Skip to content

Commit e29a074

Browse files
committed
Runtime 936 ms (Top 92.66%) | Memory 33.0 MB (Top 5.1%)
1 parent 819dd0d commit e29a074

File tree

1 file changed

+16
-35
lines changed

1 file changed

+16
-35
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,20 @@
1-
**class Solution:
2-
def largestRectangleArea(self, h: List[int]) -> int:
3-
stack,n=[],len(h)
4-
left,right=[0]*n,[0]*n
1+
class Solution:
2+
def largestRectangleArea(self, heights: List[int]) -> int:
3+
maxArea = 0
4+
stack = [] # (index, height)
55

6-
for i in range(n):
7-
if len(stack)==0:
8-
left[i]=0
9-
else:
10-
while(len(stack)!=0 and h[stack[-1]]>=h[i]):
11-
stack.pop()
12-
if len(stack)==0:
13-
left[i]=0
14-
else:
15-
left[i]=stack[-1]+1
16-
stack.append(i)
6+
for i, h in enumerate(heights):
7+
startIndex = i
8+
while stack and stack[-1][1] > h:
9+
index, height = stack.pop()
10+
maxArea = max(maxArea, height * (i - index))
11+
startIndex = index
12+
stack.append((startIndex, h))
1713

18-
while(stack):
19-
stack.pop()
14+
15+
16+
for index, height in stack:
17+
maxArea = max(maxArea, height * (len(heights) - index))
2018

21-
for i in range(n-1,-1,-1):
22-
if len(stack)==0:
23-
right[i]=n-1
24-
else:
25-
while(len(stack)!=0 and h[stack[-1]]>=h[i]):
26-
stack.pop()
27-
if len(stack)==0:
28-
right[i]=n-1
29-
else:
30-
right[i]=stack[-1]-1
31-
stack.append(i)
3219

33-
print(left)
34-
print(right)
35-
36-
area=0
37-
for i in range(n):
38-
area=max(area,h[i]*(right[i]-left[i]+1))
39-
return area**
20+
return maxArea

0 commit comments

Comments
 (0)