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
.
The basic idea to maintain a stack which only stores the increasing numbers' index and calculate the invalid index number's area on-fly. Because small values can cover large range of indexes then larger values.
In the given example: (stack stores the index number)
maxArea = 0, Stack [0] , i = 1 (i is the index for the given heights)
heights[1] < heights[stack.top()] ---> we need to pop stack.top out and at the same time calculate the top values' area.
maxArea: 2, stack[1], i = 2;
heights[i] > heights[stack.top()] --> push i into stack.
maxArea: 2, stack[1, 2], i = 3;
heights[i] > heights[stack.top()] --> push i into stack
maxArea 2, stack[1, 2, 3], i =4 // in this case, we need to consider the stack.empty case.
heights[i] < heights[stack.top()] --> we need to pop out all the stack values which is larger then current value.
maxArea 10, stack[1, 4] , i = 5
heights[i] > heights[stack.top()] --> push i into stack.
maxArea 10, stack [1, 4, 5], i = 6.
Now, we need to pop value one by one and caculate the maxArea.
#include <vector> #include <stack> #include <iostream> #include <climits> using namespace std; /* 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. */ int largestRectangleArea(vector<int>& heights) { stack<int> index; int n = heights.size(); int maxArea = 0; int i = 0; while(i < n) { while(!index.empty() && (heights[i] < heights[index.top()])) { int tmp = index.top(); index.pop(); maxArea = max(maxArea, heights[tmp] * (i - (index.empty() ? 0 : index.top() + 1))); } index.push(i++); } while(!index.empty()) { int tmp = index.top(); index.pop(); maxArea = max(maxArea, heights[tmp] * (n - (index.empty() ? 0 : index.top() + 1))); } return maxArea; } int main(void) { vector<int> heights{2, 1, 5, 6, 2, 3}; cout << largestRectangleArea(heights) << endl; }