# Hard-题目27：84. Largest Rectangle in Histogram

69人阅读 评论(0)

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.

class Solution {
public:
int largestRectangleArea(vector<int> &height) {
if(height.size() == 0) return 0;
stack<int> st;
int MAX = 0;
height.push_back(0);
int leftarea = 0, rightarea = 0;
for(int i = 0; i < height.size(); ++i){
while(!st.empty() && height[st.top()] > height[i]){
int tmp = st.top();
st.pop();
leftarea = (st.empty() ? tmp + 1 : tmp - st.top()) * height[tmp]; //以tmp为高度，tmp所在柱以及向左延伸出来的矩形面积
rightarea = (i - tmp - 1) * height[tmp]; //以tmp为高度，向右边延伸出来的矩形面积
if((leftarea + rightarea) > MAX) MAX = (leftarea + rightarea);
}
st.push(i);
}
return MAX;
}
};

24ms,18.83%,24ms,58.54%
cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64119次
• 积分：3285
• 等级：
• 排名：第10726名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论