File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ ## 暴力法
4
+ def largest_rectangle_area (heights : List [int ]) -> int :
5
+ if not heights :
6
+ return 0
7
+
8
+ max_area = 0
9
+ for i in range (len (heights )):
10
+ right_i = i
11
+ left_i = i
12
+ while right_i < len (heights ) - 1 and heights [right_i + 1 ] >= heights [i ] :
13
+ right_i += 1
14
+ while left_i > 0 and heights [left_i - 1 ] >= heights [i ]:
15
+ left_i -= 1
16
+ max_area = max (max_area , ( right_i - left_i + 1 ) * heights [i ])
17
+
18
+ return max_area
19
+
20
+ heights = [2 ,1 ,5 ,6 ,2 ,3 ]
21
+ print (largest_rectangle_area (heights ))
22
+
23
+
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ ## 利用单调Stack
4
+ def largest_rectangle_area (heights ):
5
+ stack = []
6
+ max_area = 0
7
+ index = 0
8
+
9
+ while index < len (heights ):
10
+ if not stack or heights [stack [- 1 ]] <= heights [index ]:
11
+ stack .append (index )
12
+ index += 1
13
+ else :
14
+ top_index = stack .pop ()
15
+ area = heights [top_index ] * (index - stack [- 1 ] - 1 if stack else index )
16
+ max_area = max (max_area , area )
17
+
18
+ while stack :
19
+ top_index = stack .pop ()
20
+ area = heights [top_index ] * (index - stack [- 1 ] - 1 if stack else index )
21
+ max_area = max (max_area , area )
22
+
23
+ return max_area
24
+
25
+
26
+
27
+ heights = [2 ,1 ,5 ,6 ,2 ,3 ]
28
+ print (largest_rectangle_area (heights ))
29
+
30
+
You can’t perform that action at this time.
0 commit comments