原题题目

代码实现(首刷TLE 88/96)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int size = heights.size(),ret = 0;
for(int i=0;i<size;++i)
{
ret = max(heights[i],ret);
int temp = heights[i];
for(int j=i-1;j>=0;--j)
{
temp = min(temp,heights[j]);
ret = max(temp*(i-j+1),ret);
}
}
return ret;
}
};
代码实现(首刷绝大部分看解C++)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> s;
heights.insert(heights.begin(),0);
heights.emplace_back(0);
int size = heights.size(),ret = 0;
for(int i=0;i<size;++i)
{
while(s.size() && heights[s.top()] >heights[i])
{
int cur = s.top();
s.pop();
int right = i;
int left = s.top();
ret = max(ret,(right - left - 1) * (heights[cur]));
}
s.emplace(i);
}
return ret;
}
};
代码实现(二刷绝大部分看解 DAY 170 C++)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ret = 0,left = 0,right = 0;
heights.insert(heights.begin(),0);
heights.emplace_back(0);
stack<int> s;
s.emplace(0);
for(int i=0;i<heights.size();++i)
{
while(s.size() && heights[s.top()] > heights[i])
{
int cur = s.top();
s.pop();
int left = s.top();
ret = max(ret,(i-left-1)*heights[cur]);
}
s.emplace(i);
}
return ret;
}
};
代码实现(三刷看解 DAY 255 C++)
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(),0);
heights.emplace_back(0);
stack<int> stack;
stack.emplace(0);
int size = heights.size();
int ret = 0;
for(int i = 0;i < size;++i)
{
while(stack.size() && heights[stack.top()] > heights[i])
{
int cur = stack.top();
stack.pop();
int left = stack.top();
ret = max(ret,(i - left - 1) * heights[cur]);
}
stack.emplace(i);
}
return ret;
}
};