艾恩凝
个人博客 https://aeneag.xyz/
公众号 技术乱舞
每日一练,保持手感
2021/10/16
题目
https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
题目分析
单调栈,入栈规则从小到大
题解
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0 ,len = heights.size();
stack<int> my_stack;
vector<int> new_heights(len+2,0);
for(int i = 1 ; i < len + 1 ; ++i)new_heights[i] = heights[i-1];
for(int i = 0 ; i < len+2 ; ++i){
while(!my_stack.empty() && new_heights[i] < new_heights[my_stack.top()]){
int cur = my_stack.top();
my_stack.pop();
int cur_height = new_heights[cur];
int left = my_stack.top();
int right = i;
int width = right - left - 1;
res = max(res,cur_height*width);
}
my_stack.push(i);
}
return res;
}
};
欢迎关注 #公众号:技术乱舞 一起交流
灵魂碰撞