Largest Rectangle Histogram leetcode solution
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 findMinimum(vector<int> v)
{
int min=INT_MAX;
for(int i=0;i<v.size();i++)
{
if(v[i] < min)
min=v[i];
}
return min;
}
int largestRectangleArea(vector<int> &height) {
int maxArea=0;
if(height.empty())
return 0;
int size=height.size();
int **P;
P=(int **)malloc(sizeof(int)*size);
for (int i=0 ; i < size ; i++)
{
P[i]=(int *)malloc(sizeof(int)*size);
}
vector<int> temp;
for (int i=0 ; i < size ; i++)
{
temp.clear();
for (int j=i ; j < size ; j++)
{
if(i==j)
{
P[i][j]=height[i];
if(P[i][j] > maxArea)
maxArea=P[i][j];
temp.push_back(P[i][j]);
continue;
}
temp.push_back(height[i]);
P[i][j]=findMinimum(temp)*(j-i+1);
if(P[i][j] > maxArea)
maxArea=P[i][j];
};
}
return maxArea;
}
// O(n) solution using Stack data structure
int largestRectangleArea(vector<int> &hist)
{
// Create an empty stack. The stack holds indexes of hist[] array
// The bars stored in stack are always in increasing order of their
// heights.
int n=hist.size();
stack<int> s;
int max_area = 0; // Initalize max area
int tp; // To store top of stack
int area_with_top; // To store area with top bar as the smallest bar
// Run through all bars of given histogram
int i = 0;
while (i < n)
{
// If this bar is higher than the bar on top stack, push it to stack
if (s.empty() || hist[s.top()] <= hist[i])
s.push(i++);
// If this bar is lower than top of stack, then calculate area of rectangle
// with stack top as the smallest (or minimum height) bar. ‘i’ is
// ‘right index’ for the top and element before top in stack is ‘left index’
else
{
tp = s.top(); // store the top index
s.pop(); // pop the top
// Calculate the area with hist[tp] stack as smallest bar
area_with_top = hist[tp] * (s.empty() ? i : i – s.top() – 1);
// update max area, if needed
if (max_area < area_with_top)
max_area = area_with_top;
}
}
// Now pop the remaining bars from stack and calculate area with every
// popped bar as the smallest bar
while (s.empty() == false)
{
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i – s.top() – 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
}