forked from sharunrajeev/YourFirstContribution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestrectangleinhistogram.py
More file actions
35 lines (30 loc) · 1.05 KB
/
largestrectangleinhistogram.py
File metadata and controls
35 lines (30 loc) · 1.05 KB
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
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
# left boundary => next smaller element to left
stack = []
nextSmallerLeft = [0]*n
for i in range(n):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
if stack:
nextSmallerLeft[i] = stack[-1] + 1
stack.append(i)
# right boundary => next smaller element to right
stack = []
nextSmallerRight = [n-1]*n
for i in range(n-1, -1, -1):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
if stack:
nextSmallerRight[i] = stack[-1] - 1
stack.append(i)
res = heights[0]
for i in range(n):
height = heights[i]
weidth = nextSmallerRight[i] - nextSmallerLeft[i] + 1
area = height * weidth
res = max(res, area)
return res
# Time: O(N)
# Space: O(N)