10
10
11
11
"""
12
12
13
- # hist represented as ith bar has height h(i)
13
+ # hist represented as ith bar has height h(i)
14
14
histogram = [6 , 4 , 2 , 1 , 3 , 4 , 5 , 2 , 6 ]
15
15
16
16
"""
21
21
4. compute max area
22
22
"""
23
23
24
- def get_L (hist ):
25
- L = [0 ]* len (hist )
26
- for i in range (1 , len (hist )):
27
- if hist [i ] > hist [i - 1 ]:
28
- L [i ] = i
24
+
25
+ def find_Li (hist , i ):
26
+ left_edge = 0
27
+ for j in range (i - 1 , - 1 , - 1 ):
28
+ if hist [j ] >= hist [i ]:
29
+ left_edge += 1
29
30
else :
30
- L [i ] = L [i - 1 ]
31
- return L
31
+ return left_edge
32
+
33
+ return left_edge
32
34
33
- print get_L (histogram )
34
35
35
36
def find_Ri (hist , i ):
36
37
right_edge = 0
37
- for j in range (i + 1 , len (hist )):
38
+ for j in range (i + 1 , len (hist )):
38
39
if hist [j ] >= hist [i ]:
39
40
right_edge += 1
40
41
else :
41
42
return right_edge
43
+
42
44
return right_edge
43
45
46
+
44
47
def get_area (hist , i ):
45
48
return hist [i ] * (find_Li (hist , i ) + find_Ri (hist , i ) + 1 )
46
49
@@ -53,6 +56,7 @@ def get_max_area(hist):
53
56
max_area = area
54
57
return max_area
55
58
59
+
56
60
def max_rectangle_area (histogram ):
57
61
"""Find the area of the largest rectangle that fits entirely under
58
62
the histogram.
@@ -61,21 +65,21 @@ def max_rectangle_area(histogram):
61
65
stack = []
62
66
top = lambda : stack [- 1 ]
63
67
max_area = 0
64
- pos = 0 # current position in the histogram
68
+ pos = 0 # current position in the histogram
65
69
for pos , height in enumerate (histogram ):
66
- start = pos # position where rectangle starts
70
+ start = pos # position where rectangle starts
67
71
while True :
68
- if not stack or height > top (). height :
69
- stack .append (Info (start , height )) # push
70
- elif stack and height < top (). height :
71
- max_area = max (max_area , top (). height * (pos - top (). start ))
72
+ if not stack or height > top ()[ 1 ] :
73
+ stack .append ((start , height )) # push
74
+ elif stack and height < top ()[ 1 ] :
75
+ max_area = max (max_area , top ()[ 1 ] * (pos - top ()[ 0 ] ))
72
76
start , _ = stack .pop ()
73
77
continue
74
- break # height == top().height goes here
78
+ break # height == top().height goes here
75
79
76
80
pos += 1
77
81
for start , height in stack :
78
- max_area = max (max_area , height * (pos - start ))
82
+ max_area = max (max_area , height * (pos - start ))
79
83
80
84
return max_area
81
85
0 commit comments