LeetCode: 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 height = [2,1,5,6,2,3]
,
return 10
.
地址:https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
算法: 计算以每一个bar的高为宽的最大长方形面积,则面积最大的那个即为所求的最大面积。对于以第i个bar为高的长方形可以这样求,向左找到第一个比这个bar低的bar的下标,记为left_index,向右找到第一个比这个bar低的bar的下标,记为right_index,这个bar对应的长方形面积=h[i]*(right_index-left_index)。利用栈来计算该过程可使时间复杂度达到O(n)。首先,入栈的条件是:空栈或者当前遍历的bar的高度比栈顶的高度高,若达不到上诉条件则出栈。这样就可以保证,当前遍历的节点一定是出栈元素的left_index,而出栈元素的下一个节点为right_index。代码:
1 class Solution {
2 public:
3 int largestRectangleArea(vector<int> &height) {
4 int len = height.size();
5 if(len < 1) return 0;
6 stack<int> stk;
7 int i = 0;
8 int max_area = 0;
9 while(i < len){
10 if(stk.empty() || height[stk.top()] <= height[i]){
11 stk.push(i++);
12 }else{
13 int t = stk.top();
14 stk.pop();
15 int area = height[t] * (stk.empty() ? i : i - stk.top() - 1);
16 if(area > max_area){
17 max_area = area;
18 }
19 }
20 }
21 while(!stk.empty()){
22 int t = stk.top();
23 stk.pop();
24 int area = height[t] * (stk.empty() ? len : len - stk.top() - 1);
25 if(area > max_area){
26 max_area = area;
27 }
28 }
29 return max_area;
30 }
31 };