84. 柱状图中最大的矩形
为保证权益,题目请参考 84. 柱状图中最大的矩形(From LeetCode).
解决方案1
Python
python
# 84. 柱状图中最大的矩形
# https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
# 单调栈解法
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights = heights + [0]
ans = 0
sta = [[0, -1]]
for i, height in enumerate(heights):
if sta[-1][0] < height:
sta.append([height, i])
elif sta[-1][0] == height:
sta[-1][1] = i
else:
while sta[-1][0] > height:
h, i2 = sta.pop()
ans = max(ans, (i - sta[-1][1] - 1) * h)
sta.append([height, i])
return ans
if __name__ == "__main__":
solution = Solution()
print(solution.largestRectangleArea([0]))
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
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