Skip to content

Commit 22b2805

Browse files
authored
Update Largest_Rectangle_in_Histogram.py
1 parent ca549df commit 22b2805

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed
+21-22
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
class Solution:
22
def largestRectangleArea(self, heights: List[int]) -> int:
33
'''
4-
loop through heights
5-
compare val to top val of stack. if smaller, can't continue stack height anymore
6-
pop from stack
7-
getarea
8-
popped height * (cur index - popped index)
9-
update leftmost index
10-
update max area
11-
place height, leftmost index on stack
12-
loop through stack
13-
pop val, index
14-
getarea
15-
popped height * len(array)
16-
update max area
17-
return maxarea
4+
Use stack to reference previous columns
5+
If current col >= top of stack, stack col can still be extended
6+
If current col < top of stack: stack col can't be extended anymore. Pop, extend right to get area, and update res.
7+
Pop shorter cols from stack
8+
Calculate rectangle area (current i - popped i * min(h1, h2))
9+
update largest rectangle
10+
repeat until all shorter cols have been popped
11+
Trick: When pushing to stack, push earliest popped i (current i if none were popped). This is to account for extending a column backwards to cover popped columns.
12+
remaining cols in stack can be extended to end of array
13+
14+
O(N) Time. 1 Pass with stack
15+
O(N) Space. Stack can hold up to N columns at once.
1816
'''
1917

2018
stack = []
2119
res = 0
22-
for i, height in enumerate(heights):
23-
leftmostI = i
24-
while stack and stack[-1][1] > height:
20+
for i, h in enumerate(heights):
21+
tempI = i
22+
while stack and stack[-1][1] > h:
2523
poppedI, poppedH = stack.pop()
26-
area = poppedH * (i - poppedI)
24+
area = (i - poppedI) * poppedH
2725
res = max(res, area)
28-
leftmostI = poppedI
29-
stack.append([leftmostI, height])
26+
tempI = poppedI
27+
stack.append((tempI, h))
3028
while stack:
3129
poppedI, poppedH = stack.pop()
32-
area = poppedH * len(heights)
33-
res = max(res, poppedH * (len(heights) - poppedI))
30+
area = (len(heights) - poppedI) * poppedH
31+
32+
res = max(area, res)
3433
return res

0 commit comments

Comments
 (0)