Skip to content

Commit e56d90b

Browse files
committed
feat: largest-rectangle-in-histogram
1 parent 8741184 commit e56d90b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Diff for: stack.largest-rectangle-in-histogram.py

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
84. 柱状图中最大的矩形
6+
https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
7+
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
8+
求在该柱状图中,能够勾勒出来的矩形的最大面积。
9+
"""
10+
# 单调栈,单向递增栈,只要找到每根柱子左右两边第一个小于当前柱子高度的作为左右边界
11+
def largestRectangleArea(self, heights: List[int]) -> int:
12+
size = len(heights)
13+
res = 0
14+
heights = [0] + heights + [0]
15+
# 先放入哨兵结点,在循环中就不用做非空判断
16+
stack = [0]
17+
size += 2
18+
19+
for i in range(1, size):
20+
# 如果新元素小于栈顶元素
21+
while heights[i] < heights[stack[-1]]:
22+
# 弹出栈顶元素
23+
cur_height = heights[stack.pop()]
24+
# i是栈顶元素的右边界,即右边第一个小于栈顶元素的高度
25+
cur_width = i - stack[-1] - 1
26+
res = max(res, cur_height * cur_width)
27+
stack.append(i)
28+
return res
29+
30+
# 暴力破解,找每根柱子的左右边界
31+
def largestRectangleAreaByForce(self, heights: List[int]) -> int:
32+
length = len(heights)
33+
if length == 0:
34+
return 0
35+
36+
if length == 1:
37+
return heights[0]
38+
39+
res = 0
40+
for i in range(length):
41+
# 找左边最后一个大于等于heights[i]的下标
42+
left = i
43+
while left > 0 and heights[left - 1] >= heights[i]:
44+
left -= 1
45+
46+
# 找右边最后一个大于等于heights[i]的下标
47+
right = i
48+
while right < length - 1 and heights[right + 1] >= heights[i]:
49+
right += 1
50+
51+
width = right - left + 1
52+
res = max(res, width * heights[i])
53+
54+
return res
55+
# 暴力破解,穷举
56+
def largestRectangleAreaByExhaustive(self, heights: List[int]) -> int:
57+
if len(heights) == 1:
58+
return heights[0]
59+
60+
maxRes = 0
61+
for i in range(len(heights)):
62+
minHeight = heights[i]
63+
maxRes = max(minHeight, maxRes)
64+
if (i + 1) == len(heights): break
65+
for j in range(i + 1, len(heights)):
66+
minHeight = min(minHeight, heights[j])
67+
maxRes = max(minHeight * (j - i + 1), maxRes)
68+
69+
return maxRes
70+
71+
72+
so = Solution()
73+
print(so.largestRectangleArea([1, 2, 7, 8, 9, 2, 3]))

0 commit comments

Comments
 (0)