Skip to content

Commit af38222

Browse files
committed
update
1 parent a3812cb commit af38222

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

29. 柱状图中最大的矩形.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
***给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。求在该柱状图中,能够勾勒出来的矩形的最大面积。***
2+
3+
![algo12](./images/algo12.jpg)
4+
5+
```
6+
输入:heights = [2,1,5,6,2,3]
7+
输出:10
8+
解释:最大的矩形为图中红色区域,面积为 10
9+
```
10+
11+
```
12+
class Solution:
13+
#利用单调栈+哨兵,找到比当前高度小的左右最近索引。首尾加两个0,在结束后,栈一定为空!
14+
def largestRectangleArea(self, heights: List[int]) -> int:
15+
heights = [0] + heights + [0]
16+
stack = []
17+
res = 0
18+
for i in range(len(heights)):
19+
while stack and heights[i] < heights[stack[-1]]:
20+
tmp = stack.pop()
21+
res = max(res, (i-stack[-1]-1)*heights[tmp])
22+
stack.append(i)
23+
return res
24+
```

images/algo12.jpg

12.2 KB
Loading

0 commit comments

Comments
 (0)