84. 柱状图中最大的矩形 - 力扣(LeetCode)
状态:查看思路Debug后AC。
这道题和接雨水类似,不同之处是找左右两边第一个小于栈顶元素的柱子,注意要在数组头和尾插入一个0元素以应对数组原本递增或递减的情况,代码如下:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int maxn = 0;
stack<int> st;
heights.insert(heights.begin(), 0);
heights.push_back(0);
int len = heights.size();
for(int i = 0; i < len; ++i){
while(!st.empty() && heights[st.top()] > heights[i]){
int mid = st.top();
st.pop();
int h = heights[mid];
int w = i - st.top() - 1;
maxn = max(maxn, h*w);
}
st.push(i);
}
return maxn;
}
};