forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest_rectangle_area_in_histogram.py
47 lines (28 loc) · 1.14 KB
/
largest_rectangle_area_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
'''
Largest rectangle area in a histogram::
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit.
'''
def max_area_histogram(histogram):
stack = list()
max_area = 0 # Initialize max area
index = 0
while index < len(histogram):
if (not stack) or (histogram[stack[-1]] <= histogram[index]):
stack.append(index)
index += 1
else:
top_of_stack = stack.pop()
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
max_area = max(max_area, area)
while stack:
top_of_stack = stack.pop()
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
max_area = max(max_area, area)
return max_area
hist = [4, 7, 1, 8, 4, 9, 5]
print("Maximum area is",
max_area_histogram(hist))