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
.
int largestRectangleArea(vector<int> &height)
{
if(height.size() == 0)
{
return 0;
}
int size = (int)height.size();
stack<int> myStack;
int maxValue = 0;
for(int i = 0; i < size; i++)
{
if(myStack.empty() || height[i] >= height[myStack.top()])
{
myStack.push(i);
}
else
{
while(!myStack.empty() && height[i] < height[myStack.top()])
{
int temp = height[myStack.top()];
myStack.pop();
int tempValue = temp * (!myStack.empty() ? i - myStack.top() - 1 : i);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
myStack.push(i);
}
}
while(!myStack.empty())
{
int index = myStack.top();
int temp = height[index];
myStack.pop();
int tempValue = temp * (!myStack.empty() ? size - myStack.top() - 1 : size);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
return maxValue;
}