leetcode 84 Largest Rectangle in Histogram
2016-06-30 21:15
309 查看
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.
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram.png)
Above is a histogram where width of each bar is 1, given height =
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram_area.png)
The largest rectangle is shown in the shaded area, which has area =
For example,
Given heights =
return
Subscribe to see which companies asked this question
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
vector<int> stack;
int len = heights.size();
if(len == 0) return 0;
int index = 0, max_area = 0;
heights.push_back(-1);
while (index <= len) {
if(stack.empty() || heights[index] >= heights[stack.back()]) {
stack.push_back(index);
index++;
} else {
int top = stack.back(), temp = 0;
stack.pop_back();
if(stack.empty()) {
temp = heights[top]*index;
} else {
temp = heights[top]*(index-stack.back()-1);
}
if(max_area < temp) max_area = temp;
}
}
return max_area;
}
};
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram.png)
Above is a histogram where width of each bar is 1, given height =
[2,1,5,6,2,3].
![](http://www.leetcode.com/wp-content/uploads/2012/04/histogram_area.png)
The largest rectangle is shown in the shaded area, which has area =
10unit.
For example,
Given heights =
[2,1,5,6,2,3],
return
10.
Subscribe to see which companies asked this question
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
vector<int> stack;
int len = heights.size();
if(len == 0) return 0;
int index = 0, max_area = 0;
heights.push_back(-1);
while (index <= len) {
if(stack.empty() || heights[index] >= heights[stack.back()]) {
stack.push_back(index);
index++;
} else {
int top = stack.back(), temp = 0;
stack.pop_back();
if(stack.empty()) {
temp = heights[top]*index;
} else {
temp = heights[top]*(index-stack.back()-1);
}
if(max_area < temp) max_area = temp;
}
}
return max_area;
}
};
相关文章推荐
- Myeclipse安装 配置Maven
- QLineEdit显示位置简介
- 谈谈Backlog梳理活动
- [从codewars学习到的JS系列2]正则表达式中的exec()与字符串的match()方法区别
- leetcode 367 Valid Perfect Square
- ios调用unix 网络编程的socket 接口实行UDP通信, 锁屏后解屏会闪退的解决方法
- centos 7 启动盘制作和grub rescue引导恢复
- 振动器 Vibrator
- spring mybatis mapper接口注解方式注入
- 编辑文本框多行显示,带边框
- NoSql之Redis集群搭建
- selenium测试环境搭建(一)
- DP 练习 uva103 Stacking Boxs
- Unity脚本基础知识思维导图1.0
- Linux --- strace 工具
- PHP接触
- 0630第五讲继承(4)抽象基类、纯虚函数、多继承
- 一些有趣的智力题
- Input输入设置
- csdn常用网址归纳,csdn导航