leetcode之Largest Rectangle in Histogram
source link: https://blog.csdn.net/yanxiangtianji/article/details/8575070
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
原载于http://blog.csdn.net/yanxiangtianji
转载请注明出处
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
.
穷举各个segment,共二分之n平方个(O(n^2)),在每个segment里面找到最小高度(O(n)),可以优化到O(1)。找高度与segment长度之积最大的。
总体时间复杂度为O(n^3),可以优化到O(n^2);空间复杂度O(1)。
优化后(O(n^2)):
目标即为找到最大的l*f(p,l)值。其中p=1...n;l=1...p。
状态转移方程:
f(p,l) = 当l不为1:min( f(p-1,l-1), height[p] )
当l为1:height[p]
时间复杂度O(n^2);空间复杂度为O(n^2),考虑到只是用了f(p-1,*),空间可以压缩到O(n)。
具体压缩方法(用dp表示f):
去掉p这个维度,l从大到小迭代,此时访问dp[l-1]即为访问f(p-1,l-1)。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK