Skip to content

Commit 8aae3c1

Browse files
committed
update
1 parent 09da8d8 commit 8aae3c1

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

stack/largest_rectangle_area_v2.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@ def largest_rectangle_area(heights):
1313
else:
1414
top_index = stack.pop()
1515
area = heights[top_index] * (index - stack[-1] - 1 if stack else index)
16+
print(heights[top_index] , (index - stack[-1] - 1 if stack else index))
1617
max_area = max(max_area, area)
1718

19+
1820
while stack:
1921
top_index = stack.pop()
2022
area = heights[top_index] * (index - stack[-1] - 1 if stack else index)
23+
print(heights[top_index] , (index - stack[-1] - 1 if stack else index))
2124
max_area = max(max_area, area)
2225

2326
return max_area
@@ -26,5 +29,41 @@ def largest_rectangle_area(heights):
2629

2730
heights = [2,1,5,6,2,3]
2831
print(largest_rectangle_area(heights))
32+
33+
#[]
34+
#[0]
35+
#[]
36+
#[1]
37+
#[1, 2]
38+
#[1, 2, 3]
39+
#[1, 2]
40+
#[1]
41+
#[1, 4]
42+
#[1, 4, 5]
43+
#[1, 4]
44+
#[1]
45+
#10
2946

3047

48+
#0
49+
#0
50+
#2
51+
#2
52+
#2
53+
#2
54+
#6
55+
#10
56+
#10
57+
#10
58+
#10
59+
#10
60+
#10
61+
62+
63+
#2 1
64+
#6 1
65+
#5 2
66+
#3 1
67+
#2 4
68+
#1 6
69+
#10

stack/test.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from typing import List
2+
3+
## 利用单调Stack
4+
def largest_rectangle_area(heights):
5+
stack = []
6+
index = 0
7+
max_area = 0
8+
while index < len(heights):
9+
if not stack or heights[index] >= heights[stack[-1]]:
10+
stack.append(index)
11+
index += 1
12+
else:
13+
stack_top_index = stack.pop()
14+
area = heights[stack_top_index] * ( index - stack[-1] -1 if stack else index)
15+
max_area = max(max_area , area)
16+
17+
while stack:
18+
stack_top_index = stack.pop()
19+
area = heights[stack_top_index]
20+
max_area = max(max_area , area)
21+
22+
return max_area
23+
24+
25+
26+
27+
28+
29+
30+
31+
32+
33+
heights = [2,1,5,6,2,3]
34+
print(largest_rectangle_area(heights))

单调栈的说明.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## 单调栈 计算最大矩形面积
2+
- 我们使用一个单调递增栈来存储直方图中元素的索引。
3+
- 我们从左到右遍历直方图,当当前元素大于或等于栈顶元素时,我们将其推入栈中。
4+
- 当当前元素小于栈顶元素时,我们开始计算以栈顶元素为高度的最大矩形面积。我们不断弹出栈顶元素,直到找到一个小于当前元素的元素为止。对于每个弹出的元素,我们计算以它为高度的最大矩形面积,并更新最大面积。
5+
- 当遍历完整个直方图后,我们还需要处理栈中剩余的元素,计算以它们为高度的最大矩形面积。
6+
- 最终返回找到的最大矩形面积。
7+
- 这个算法的时间复杂度是 O(n),因为我们只需要遍历一遍直方图,每个元素最多进出栈一次。空间复杂度是 O(n),因为我们使用了一个栈来存储元素索引。

0 commit comments

Comments
 (0)