File tree 1 file changed +16
-35
lines changed
scripts/algorithms/L/Largest Rectangle in Histogram
1 file changed +16
-35
lines changed Original file line number Diff line number Diff line change 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)
5
5
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 ))
17
13
18
- while (stack ):
19
- stack .pop ()
14
+
15
+
16
+ for index , height in stack :
17
+ maxArea = max (maxArea , height * (len (heights ) - index ))
20
18
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 )
32
19
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
You can’t perform that action at this time.
0 commit comments