给出 n 个非负整数来表示柱状图的各个柱子的高度,每个柱子紧挨彼此,且宽度为 1 。
您的函数要能够求出该柱状图中,能勾勒出来的最大矩形的面积。

详见:https://leetcode.com/problems/largest-rectangle-in-histogram/description/

Java实现:

方法一:遍历数组,每找到一个局部峰值,就向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值。

class Solution {
public int largestRectangleArea(int[] heights) {
int res=0;
int n=heights.length;
for(int i=0;i<n;++i){
if(i+1<n&&heights[i]<=heights[i+1]){
continue;
}
int minH=heights[i];
for(int j=i;j>=0;--j){
minH=Math.min(minH,heights[j]);
int area=minH*(i-j+1);
res=Math.max(res,area);
}
}
return res;
}
}

方法二:

class Solution {
public int largestRectangleArea(int[] heights) {
int n=heights.length;
if (heights == null || n == 0){
return 0;
}
int res=0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < n; ++i) {
//如果高度递增,那么一次入栈。
if (stack.isEmpty() || heights[stack.peek()] <= heights[i]) {
stack.push(i);
}
//如果当前柱比栈顶的低,那么把栈顶的拿出来,计算所有已经出栈的最大面积。
else {
int start = stack.pop();
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
res = Math.max(res, heights[start] * width);
--i;
}
} //循环过后栈中是递增的条目,计算在栈中递增条目的最大面积。
while (!stack.isEmpty()) {
int start = stack.pop();
int width = stack.isEmpty() ? n : n - stack.peek() - 1;
res = Math.max(res, heights[start] * width);
}
return res;
}
}

参考:https://www.cnblogs.com/grandyang/p/4322653.html

最新文章

  1. linux bash 笔记
  2. iOS 常见 Crash 及解决方案
  3. [转载] C++位运算:将一个4字节整数的二进制表示中的001替换为011
  4. 高版本myeclipse破解以及优化
  5. .Net 代码安全保护产品DNGuard HVM使用
  6. Map集合中value()方法与keySet()、entrySet()区别
  7. Eclipse vim插件安装使用
  8. python作业day4计算器
  9. 教你在mac上配置adb环境变量
  10. webBrowser中操作网页元素全攻略
  11. iOS多线程与网络开发之发送接收server信息
  12. bat给文件追加换行内容
  13. python subprocess.Popen 控制台输出 实时监控百度网ping值
  14. 各种MM(存储器)含义
  15. Tensorflow 中的优化器解析
  16. 点击DIV随机换颜色
  17. crontab详细用法
  18. intellij 快捷键整理
  19. nuclio dokcer 运行测试
  20. [SCOI2007]修车(建图好题)

热门文章

  1. Myeclipse+TestNG白盒测试环境搭建
  2. spring 从jsp到jsp
  3. MongoDB 2.6复制集单节点部署(三)
  4. dos窗口的乱码问题
  5. C#视频取帧图
  6. AngularJS系统学习之Scope(作用域)
  7. 1.17 shell action
  8. 5、html的body内标签之多行文本及下拉框
  9. 面试lua笔试题各种坑
  10. dead code 死代码 无作用的代码