Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/coding_made_simple/max_rect_area.py
1240 views
1
"""
2
Title: Maximum Rectangular Area in Histogram
3
Video link: https://youtu.be/ZmnqCZp9bBs
4
5
Java code: https://github.com/mission-peace/interview/blob/master/src/com/interview/stackqueue/MaximumHistogram.java
6
7
"""
8
9
class MaximumHistogram:
10
11
def maxHistogram(self, _input):
12
stack = []
13
max_area = 0
14
area = 0
15
i = 0
16
while i < len(_input):
17
if len(stack) == 0 or stack[-1] <= _input[i]:
18
stack.append(i)
19
i += 1
20
else:
21
top = stack.pop(-1)
22
23
if len(stack) == 0:
24
area = _input[top] * i
25
else:
26
area = _input[top] * (i - stack[-1] - 1)
27
28
max_area = max(area, max_area)
29
30
while stack:
31
top = stack.pop(-1)
32
33
if len(stack) == 0:
34
area = _input[top] * i
35
else:
36
area = _input[top] * (i - stack[-1] - 1)
37
38
max_area = max(area, max_area)
39
40
return max_area
41
42
43
if __name__ == "__main__":
44
_input = [2,2,2,6,1,5,4,2,2,2,2]
45
mh = MaximumHistogram()
46
print((mh.maxHistogram(_input)))
47
assert mh.maxHistogram(_input) == 12, "Algorithm did not specify the correct result."
48
49
50
51
52
53
54