Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.算法
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.app
最简单的天然是暴力法,即穷举左端坐标和右端坐标,计算两个坐标之间矩形的最大面积,再从全部的面积中得出最大的即为解。可是该方法至少须要两个for
循环来遍历每一种左右端的组合,时间复杂度为O($n^2$)。如下是该方法的代码,解是对的,但在leetcode上会超时。spa
class Solution: # @param height, a list of integer # @return an integer def largestRectangleArea(self, height): length = len(height) max_area = -1 for i in range(length): for j in range(i + 1, length): h = min(height[i: j]) area = h * (j - i) if max_area < area: max_area = area return max_area
能够考虑,计算一个矩形的面积时,好比图
中的斜线部分,其两侧的高度必定是低于矩形所在的矩形条的高度的,所以能够经过维护一个栈来得出左端左边及右端坐标和矩形的高度,每个矩形条只进栈一次,这样时间复杂度为O(n)。
1. 算法从左向右遍历每一个矩形,以当前遍历的位置为右端坐标,若是栈为空或者当前矩形不低于栈顶的矩形,则将当前的位置坐标压栈,由于此时的坐标必定不是右边界(指要计算的面积右边的一个矩形条,不包含在要计算的面积中),例如图中,加入当前坐标为3
,高度为6
,栈顶坐标的高度为5
,那么当前矩形条不可能做为右边界,将其压栈。
2. 若是当前位置的矩形低于栈顶的矩形条,那么当前位置能够做为一个矩形的边界,则从这个位置开始向左遍历,对每一个高度大于右边界的矩形条做为左边界计算一次面积,直到高度小于右边界或栈为空。
3. 在遍历过一遍以后,若是栈不为空,则以栈中的每一个坐标做为左边界计算一次面积,结合步骤2得出最大面积。
Accepted code以下:code
class Solution: # @param height, a list of integer # @return an integer def largestRectangleArea(self, height): max_area = 0 i = 0 n = len(height) stack = [] while i < n: if len(stack) == 0 or height[i] >= height[stack[-1]]: stack.append(i) i += 1 else: top = stack.pop() area_with_top = height[top] * (i if len(stack) == 0 else i - stack[-1] - 1) if max_area < area_with_top: max_area = area_with_top while len(stack) != 0: top = stack.pop() area_with_top = height[top] * (i if len(stack) == 0 else i - stack[-1] - 1) if max_area < area_with_top: max_area = area_with_top return max_area
这个方法并非提供一个准确的找出最大的矩形的算法,而是经过试验那些“可能”成为最大的矩形的面积,再从其中找出最大的。而最大的矩形必定知足两个边界的高度小于该矩形的高度这个条件(若是不知足的话,边界也能够被添加进来计算而不破坏矩形的形状,此时不为最大),所以找出全部这样的矩形就必定能够在其中找出面积最大的矩形。leetcode