Skip to content

Commit af25f1d

Browse files
committed
Largest Rectangle in Histogram
1 parent 6faf33e commit af25f1d

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/largest-rectangle-in-histogram/
3+
4+
Given an array of integers heights representing the histogram's bar height where the width of each
5+
bar is 1, return the area of the largest rectangle in the histogram.
6+
7+
Example 1:
8+
Input: heights = [2,1,5,6,2,3]
9+
Output: 10
10+
Explanation: The above is a histogram where width of each bar is 1.
11+
The largest rectangle is shown in the red area, which has an area = 10 units.
12+
13+
Example 2:
14+
Input: heights = [2,4]
15+
Output: 4
16+
17+
Constraints:
18+
1 <= heights.length <= 105
19+
0 <= heights[i] <= 104
20+
"""
21+
# Time Complexity: O(N)
22+
23+
class Solution:
24+
def largestRectangleArea(self, heights: List[int]) -> int:
25+
lb = [] # left boundary
26+
stack = []
27+
28+
for index in range(len(heights)):
29+
while stack and heights[stack[-1]] >= heights[index]:
30+
stack.pop()
31+
32+
lb.append(stack[-1] if stack else -1)
33+
stack.append(index)
34+
35+
rb = [0] * len(heights) # right boundary
36+
stack = []
37+
38+
for index in range(len(heights)-1, -1, -1):
39+
while stack and heights[stack[-1]] >= heights[index]:
40+
stack.pop()
41+
42+
rb[index] = stack[-1] if stack else len(heights)
43+
stack.append(index)
44+
45+
max_area = 0
46+
for index in range(len(heights)):
47+
width = rb[index] - lb[index] - 1
48+
max_area = max(max_area, width * heights[index])
49+
50+
return max_area

0 commit comments

Comments
 (0)