---
layout:none
title: maximal rectangle in histogram
---
Question: 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.
Answer:
First, the brute-force solution is obvious. For each integer, find the most left element and right element
which is not less it, that forms the maximal rectangle containing this integer. Iterating the whole array and we
can find the maximal rectangle. The problem is it's two slow because its complexity is O(n2).
We need to optimize it. Here is a hint, for any rectangle that consist of continuous integers, it starts from a
integer which is bigger than its left number and ends with a integer which is bigger than its right number.
So every time we encounter a new integer, if it's bigger than or equal its left value, we can regard it as a start of new
rectangle and if it is smaller than its left value, it must be end of rectangle. We need to store these nested
rectangles and calculate the area when encountering its ending. A stack will just fit our need. Queue or a simple
array are also OK. Here's the code:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxArea = 0;
stack<int> s;
height.push_back(0);
int i = 0;
while (i < height.size()) {
if (s.empty() || height[s.top()] <= height[i]) {
s.push(i++);
} else {
int t = s.top();
s.pop();
maxArea = max(maxArea, height[t] * ((s.empty()) ? i : i - s.top() - 1));
}
}
return maxArea;
}
So, when we push another integer into stack we encounter a new rectangle. And when we pop a integer from stack,
we get start position (the next position of the most left value less than it, i.e. the next value on stack) of
one rectangle and can calculate its area. If the stack is empty, which means current value is least value ever,
which forms a rectangle from the start point of the array to current position.