leetcode 84.柱状图中的最大的矩形(python)
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]
。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10
个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
方法1:
暴力求解
#
# @lc app=leetcode.cn id=84 lang=python
#
# [84] 柱状图中最大的矩形
#
# @lc code=start
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
maxArea = 0
for i in range(len(heights)):
for j in range(i, len(heights)):
minHeight = sys.maxint
for k in range(i, j + 1):
minHeight = min(minHeight, heights[k])
maxArea = max(maxArea, minHeight * (j - i + 1))
return maxArea
方法2:
暴力加速
#
# @lc app=leetcode.cn id=84 lang=python
#
# [84] 柱状图中最大的矩形
#
# @lc code=start
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
maxArea = 0
for i in range(len(heights)):
minHeight = sys.maxint
for j in range(i, len(heights)):
minHeight = min(minHeight, heights[j])
maxArea = max(maxArea, minHeight * (j - i + 1))
return maxArea
方法3:
Stack
#
# @lc app=leetcode.cn id=84 lang=python
#
# [84] 柱状图中最大的矩形
#
# @lc code=start
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stack = [-1]
res = 0
heights.append(-1)
for idx, val in enumerate(heights):
while heights[stack[-1]] > val:
h = heights[stack.pop()]
res = max(res, h * (idx - stack[-1] - 1))
stack.append(idx)
return res