-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathlargest-rectangle.py
More file actions
47 lines (33 loc) · 1.08 KB
/
largest-rectangle.py
File metadata and controls
47 lines (33 loc) · 1.08 KB
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
#!/bin/python3
import math
import os
import random
import re
import sys
# Referenced https://www.geeksforgeeks.org/largest-rectangle-under-histogram/
def largestRectangle(heights):
stack = list()
index = 0
largest_rectangle = 0
while index < len(heights):
if (not stack) or (heights[stack[-1]] <= heights[index]):
stack.append(index)
index += 1
else:
top_of_stack = stack.pop()
area = (heights[top_of_stack] *
((index - stack[-1] - 1) if stack else index))
largest_rectangle = max(largest_rectangle, area)
while stack:
top_of_stack = stack.pop()
area = (heights[top_of_stack] *
((index - stack[-1] - 1) if stack else index))
largest_rectangle = max(largest_rectangle, area)
return largest_rectangle
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
h = list(map(int, input().rstrip().split()))
result = largestRectangle(h)
fptr.write(str(result) + '\n')
fptr.close()