-
Notifications
You must be signed in to change notification settings - Fork 0
/
q84_Largest_Rectangle_in_Histogram.py
63 lines (53 loc) · 1.7 KB
/
q84_Largest_Rectangle_in_Histogram.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
largest = {}
currh = []
for i, height in enumerate(heights):
while currh and heights[currh[-1]] > height:
currh.pop()
for h in currh:
largest[heights[h]][-1] += heights[h]
if (not currh and height > 0) or (currh and height > heights[currh[-1]]):
n = 1
s = i - 1
while s >= 0 and heights[i] <= heights[s]:
s -= 1
n += 1
if height in largest:
largest[height].append(height * n)
else:
largest[height] = [height * n]
currh.append(i)
pass
newlist = [0]
for m in list(largest.values()):
newlist += m
return max(newlist)
def largestRectangleArea1(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
currh = []
ans = 0
for i, height in enumerate(heights):
while currh and currh[-1][0] > height:
ch,j = currh.pop()
ans = max(ch*(i-j),ans)
if (not currh and height > 0) or (currh and height > currh[-1][0]):
s = i
while s > 0 and heights[i] <= heights[s-1]:
s -= 1
currh.append((height,s))
pass
i=len(heights)
while currh:
ch, j = currh.pop()
ans = max(ch * (i - j), ans)
return ans
s=[2,3,1]
print(Solution().largestRectangleArea1(s))