Description
Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Constraints:
• 1 <= heights.length <= 10
5
^5
5
• 0 <= heights[i] <= 10
4
^4
4
Example
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Submissions
解题采用栈的思路,首先遍历元素,找每个柱子对应的最大面积,然后使用递增栈完成找每个柱子的最大面积,需要在原数组后面加上一个0,是为了让最后一个元素出栈,注意宽度的计算要考虑弹出元素时栈是否为空。
用一个栈stack存储索引。新的i在入栈前,先查看新的height[i]是否小于height[stack[-1]]:若小于,i入栈;若不小于,弹出栈顶元素index,令height[index]为高,i为右边界,当前栈顶部为左边界。计算其面积并更新最大面积max_area。
实现代码如下:
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
heights.append(0)
stack = [-1]
max_area = 0
for i in range(n+1):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
max_area = max(max_area, h*w)
stack.append(i)
return max_area