# 柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]
。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10
个单位。
示例:
输入: [2,1,5,6,2,3]以下程序实现了这一功能,请你填补空白处内容: ```python class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ largest_rectangle = 0 ls = len(heights) stack = [-1] top, pos = 0, 0 for pos in range(ls): while top > 0 and heights[stack[top]] > heights[pos]: _____________________________ top -= 1 stack.pop() stack.append(pos) top += 1 while top > 0: largest_rectangle = max(largest_rectangle, heights[stack[top]] * (ls - stack[top - 1] - 1)) top -= 1 return largest_rectangle if __name__ == "__main__": s = Solution() print (s.largestRectangleArea([2,1,5,6,2,3])) ``` ## template ```python class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ largest_rectangle = 0 ls = len(heights) stack = [-1] top, pos = 0, 0 for pos in range(ls): while top > 0 and heights[stack[top]] > heights[pos]: largest_rectangle = max(largest_rectangle, heights[stack[top]] * (pos - stack[top - 1] - 1)) top -= 1 stack.pop() stack.append(pos) top += 1 while top > 0: largest_rectangle = max(largest_rectangle, heights[stack[top]] * (ls - stack[top - 1] - 1)) top -= 1 return largest_rectangle if __name__ == "__main__": s = Solution() print (s.largestRectangleArea([2,1,5,6,2,3])) ``` ## 答案 ```python largest_rectangle = max(largest_rectangle, heights[stack[top]] * (pos - stack[top - 1] - 1)) ``` ## 选项 ### A ```python largest_rectangle = max(largest_rectangle, heights[stack[top]] * (pos - stack[top] - 1)) ``` ### B ```python largest_rectangle = max(largest_rectangle, heights[stack[top]] * (pos - stack[top + 1] - 1)) ``` ### C ```python largest_rectangle = max(largest_rectangle, heights[stack[top]] * (pos - stack[top - 1] + 1)) ```
输出: 10