Skip to content

Commit d66e64a

Browse files
authored
Update 0084-柱状图中最大的矩形.py
1 parent 6287226 commit d66e64a

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed
Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,28 @@
1+
首先要想找到第 i 位置最大面积是什么
2+
是以 i 为中心向左找第一个小于 heights[i] 的位置 left_i向右找第一个小于于 heights[i] 的位置 right_i
3+
即最大面积为 heights[i] * (right_i - left_i -1)
4+
所以我们的问题就变成如何找right_i left_i
5+
6+
# 暴力解法,会超时
7+
class Solution:
8+
def largestRectangleArea(self, heights: List[int]) -> int:
9+
res = 0
10+
n = len(heights)
11+
for i in range(n):
12+
left_i = i
13+
right_i = i
14+
while left_i >= 0 and heights[left_i] >= heights[i]:
15+
left_i -= 1
16+
while right_i < n and heights[right_i] >= heights[i]:
17+
right_i += 1
18+
res = max(res, (right_i - left_i - 1) * heights[i])
19+
return res
20+
21+
# 单调栈
122
class Solution:
223
def largestRectangleArea(self, heights: List[int]) -> int:
3-
heights = [0] + heights + [0]
24+
heights = [0] + heights + [0] #如果遍历之后,栈不为空,那么还需要一步:即弹出栈中所有元素,分别计算最大面积。然而当加了两个0以后,在结束后,栈一定为空!
25+
# 因为0入栈的时候,会把前面所有的数全部弹出,如果0最后一个入栈,所有的数都会弹出;头部加0便于处理当栈里只有一个有效元素要弹出的时候计算面积
426
res = 0
527
stack = []
628
for i in range(len(heights)):
@@ -9,4 +31,4 @@ def largestRectangleArea(self, heights: List[int]) -> int:
931
res = max(res, (i - stack[-1] - 1) * heights[top])
1032

1133
stack.append(i)
12-
return res
34+
return res

0 commit comments

Comments
 (0)