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.


题解:在网上研究了好久才弄懂。

首先,需要一个栈,栈里面存放每个条的索引,当当前的元素大于栈顶的元素或者栈为空时,将当前元素入栈;

当当前元素小于栈顶元素的时候,将栈顶元素弹出来,索引记录在top变量上,那么还有两种可能:

  • 栈不为空,如下图所示,从栈顶的条到top所指的条(当前出栈的条)的高度一定大于等于top的高度(否则它们应该还在栈里面),一共有(top-栈顶索引-1)个条,而top~i这一段的高度也一定大于等于top的高度(否则指针不会有top刚出栈而指针已经移动到i),一共有(i-top)个条(包括top自己),所以top所能向左和向右到达的最大延伸长度为(top-栈顶索引-1)+(i-top)=(i-栈顶索引-1),产生的最大面积为height[top] * (i-栈顶索引-1) 。

  • 栈为空,如下图所示,说明top所指的条(当前出栈的条)向左延伸可以到达最左边,向右延伸可以到达i,一共有 i 个条,产生的最大面积为height[top] * i。

所以当元素top出栈的时候,它所能产生的最大面积为 height[top] * (stack.isEmpty()?i:i-stack.top()-1) 。

总结一下栈的意义,对于为位置 i 处的条来说,栈中存放的元素是可以一路“延展”至 i 的条,所以它们都比 i 小,都可以利用 i 来增加自己产生的矩形的最大面积,而那些比 i 高的条已经不能通过 i 继续往右延展了,即它们往右能够延展到的部分已经被 i 阻拦了,我们就可以计算它们此时已经左右延展的距离来计算它们所能产生的矩形的最大面积了。比如下图中i = 4的时候,红色的条已经不能通过4继续往右扩展,它往右扩展被4给挡住了,所以它要出栈,而绿色的条比4矮,它仍然可以利用4增大它产生的矩形的面积,所以它不需要出栈,因为我们还没确定它的右边界。

最后,有两点trick:

  • 一是比如上图的情况,遍历完成后,绿色的条还在栈里面,所以我们要在所有的条最后增加一个长度为0的条,它可以把栈中所有的条都弹出来,我们就得到了所有的条能够产生的最大矩形的面积了。
  • 二是在有元素弹出栈后,i 指针要保持不动,因为有可能它前面的元素也比 i 指向的条矮,需要出栈。

代码如下:

 public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
Stack<Integer> index = new Stack<Integer>();
int totalMax = 0;
ArrayList<Integer> newHeight = new ArrayList<Integer>();
for(int i:height) newHeight.add(i);
newHeight.add(0); for(int i = 0;i < newHeight.size();i++){
if(index.isEmpty() || newHeight.get(i) >= newHeight.get(index.peek()))
index.push(i);
else{
int top = index.pop();
totalMax = Math.max(totalMax,newHeight.get(top) * (index.isEmpty()?i:i-index.peek()-1));
i--;
}
} return totalMax;
}
}

最新文章

  1. POJ 1654 Area(水题)
  2. CSS的压缩 方法与解压
  3. storm学习-storm入门
  4. vs2010代码注释自动生成api文档
  5. insert into (select...WITH CHECK OPTION) values(...)
  6. EL表达式中的“+-x/”四种运算符和条件,比较运算符等
  7. Agri-Net poj 1258
  8. Need a code of lazy load for div--reference
  9. FZU-竞技游戏
  10. hdu1597
  11. 转: seajs知识点与cmd规范
  12. ruby the diference between gets and gets.chomp()
  13. GC Tools
  14. c++输出小数
  15. ormlite 文档
  16. Vue.js常用指令:v-show和v-if
  17. 如何利用 Visual Studio 自定义项目或工程模板(转载)
  18. 何为中间语言IL?
  19. 关于双系统下Ubuntu不能访问Windows中某个盘的问题
  20. python web中的文件上传与下载

热门文章

  1. BF的真正意义
  2. ar命令提取.o的时候报错:is a fat file (use libtool(1) or lipo(1) and ar(1) on it)
  3. UUID(即GUID)
  4. BIOS截图中文
  5. IIS管理器如何添加网站
  6. 在CentOS 5下安装中文五笔
  7. ps选框工具全解
  8. 详细解读:远程线程注入DLL到PC版微信
  9. Win7 设置、访问共享文件夹
  10. js中的DOM节点