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

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值