|
1 | 1 | class Solution:
|
2 | 2 | def largestRectangleArea(self, heights: List[int]) -> int:
|
3 | 3 | '''
|
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. |
18 | 16 | '''
|
19 | 17 |
|
20 | 18 | stack = []
|
21 | 19 | 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: |
25 | 23 | poppedI, poppedH = stack.pop()
|
26 |
| - area = poppedH * (i - poppedI) |
| 24 | + area = (i - poppedI) * poppedH |
27 | 25 | res = max(res, area)
|
28 |
| - leftmostI = poppedI |
29 |
| - stack.append([leftmostI, height]) |
| 26 | + tempI = poppedI |
| 27 | + stack.append((tempI, h)) |
30 | 28 | while stack:
|
31 | 29 | 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) |
34 | 33 | return res
|
0 commit comments