[LeetCode OJ] Largest Rectangle in Histogram

时间:2022-03-11 15:48:13

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.

[LeetCode OJ] Largest Rectangle in Histogram

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

[LeetCode OJ] Largest Rectangle in Histogram

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.

方法一:两层循环遍历,复杂度O(n2

 class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int maxArea=;
for(unsigned i=; i<height.size(); i++)
{
int min = height[i];
for(unsigned j=i; j<height.size(); j++)
{
if(height[j]<min)
min = height[j];
int area = min*(j-i+);
if(area>maxArea)
maxArea = area;
}
}
return maxArea;
}
};

方法二:用堆栈保存重要位置,复杂度O(n)

 class Solution {
public:
int largestRectangleArea(vector<int> &height) { //用堆栈来实现
stack<unsigned> st;
unsigned maxArea = ;
for(unsigned i=; i<height.size(); i++)
{
if(st.empty())
st.push(i);
else
{
while(!st.empty())
{
if(height[i]>=height[st.top()])
{
st.push(i);
break;
}
else
{
unsigned idx=st.top();
st.pop();
unsigned leftwidth = st.empty() ? idx : (idx-st.top()-);
unsigned rightwidth = i - idx-;
maxArea = max(maxArea, height[idx]*(leftwidth+rightwidth+));
}
}
if(st.empty())
st.push(i);
}
}
unsigned rightidx = height.size();
while(!st.empty())
{
unsigned idx = st.top();
st.pop();
unsigned leftwidth = st.empty() ? idx : (idx-st.top()-);
unsigned rightwidth = rightidx - idx-;
maxArea = max(maxArea, height[idx]*(leftwidth+rightwidth+));
}
return maxArea;
}
};