1010
1111"""
1212
13- # hist represented as ith bar has height h(i)
13+ # hist represented as ith bar has height h(i)
1414histogram = [6 , 4 , 2 , 1 , 3 , 4 , 5 , 2 , 6 ]
1515
1616"""
21214. compute max area
2222"""
2323
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
2930 else :
30- L [i ] = L [i - 1 ]
31- return L
31+ return left_edge
32+
33+ return left_edge
3234
33- print get_L (histogram )
3435
3536def find_Ri (hist , i ):
3637 right_edge = 0
37- for j in range (i + 1 , len (hist )):
38+ for j in range (i + 1 , len (hist )):
3839 if hist [j ] >= hist [i ]:
3940 right_edge += 1
4041 else :
4142 return right_edge
43+
4244 return right_edge
4345
46+
4447def get_area (hist , i ):
4548 return hist [i ] * (find_Li (hist , i ) + find_Ri (hist , i ) + 1 )
4649
@@ -53,6 +56,7 @@ def get_max_area(hist):
5356 max_area = area
5457 return max_area
5558
59+
5660def max_rectangle_area (histogram ):
5761 """Find the area of the largest rectangle that fits entirely under
5862 the histogram.
@@ -61,21 +65,21 @@ def max_rectangle_area(histogram):
6165 stack = []
6266 top = lambda : stack [- 1 ]
6367 max_area = 0
64- pos = 0 # current position in the histogram
68+ pos = 0 # current position in the histogram
6569 for pos , height in enumerate (histogram ):
66- start = pos # position where rectangle starts
70+ start = pos # position where rectangle starts
6771 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 ] ))
7276 start , _ = stack .pop ()
7377 continue
74- break # height == top().height goes here
78+ break # height == top().height goes here
7579
7680 pos += 1
7781 for start , height in stack :
78- max_area = max (max_area , height * (pos - start ))
82+ max_area = max (max_area , height * (pos - start ))
7983
8084 return max_area
8185
0 commit comments