Skip to content

Commit 17f133f

Browse files
committed
Largest Rectangle in Histogram
1 parent 40693b8 commit 17f133f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
3+
4+
5+
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
6+
7+
8+
The largest rectangle is shown in the shaded area, which has area = 10 unit.
9+
10+
For example,
11+
Given heights = [2,1,5,6,2,3],
12+
return 10.
13+
'''
14+
15+
class Solution(object):
16+
def largestRectangleArea(self, heights):
17+
"""
18+
:type heights: List[int]
19+
:rtype: int
20+
"""
21+
heights.append(0)
22+
stack = [-1]
23+
result = 0
24+
for i in range(len(heights)):
25+
while heights[i] < heights[stack[-1]]:
26+
h = heights[stack.pop()]
27+
w = i - stack[-1] - 1
28+
result = max(result, h * w)
29+
stack.append(i)
30+
heights.pop()
31+
return result
32+
33+
34+
if __name__ == "__main__":
35+
assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10

0 commit comments

Comments
 (0)