您的位置:首页 > 其它

Largest Rectangle in Histogram :直方图中的最大三角形

2017-09-25 16:40 393 查看
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 heights = 
[2,1,5,6,2,3]
,

return 
10
.

思路一:穷举

不写了...

思路二:维持一个递增序列,每次都在最长的递增序列中查找最大值。利用一个堆栈来保持下标。

示意图如下:(画图太费劲了,有个公众号,说的很好,在参考目录里)红色圈表示非递减序列(stack里的那部分),紫色表示寻找最值的过程(pop、Math.max里的过程)

















public static int LRiH_IncreaseStack(int[] height) {
Stack<Integer> s = new Stack<>();
int max = 0;
for (int index = 0; index <= height.length; index++) {
int height_index = (index == height.length) ? 0 : height[index];//把0当成一个高度插入,用于情况之前的序列,比如1,2,3,4,5,6,需要最后插入一个零来在该序列中寻找最大值
if (s.isEmpty() || height[s.peek()] <= height_index) {
s.push(index);
} else {
int top = s.pop();//遍历非递减序列,计算是否比历史最大值还大
max = Math.max(max, height[top] * (s.isEmpty() ? index : index - 1 - s.peek()));//index-1表示非递减序列的最大值坐标,因为下面的index--与for中的index++,所以在此大括号内是固定不变的,index-1-s.peek()由于寻找最值时不断弹栈,相当于遍历非递减序列里距离最大高度下标的各个宽度
index--;// 固定住index,一直寻找堆栈中高度大于当前位置的下表,直到堆栈中下表对应的高度低于当前位置高度(因为此时堆栈中下表可以和当前下表构成非递减序列,是潜在的最大值序列)

}
}
return max;
}
还有其他的方法。。。。。。日后再说

参考文章: 

1.https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/ 代码很简洁

2.http://chuansong.me/n/390896436960
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: