代码随想录算法训练营第六十天| 84.柱状图中最大的矩形
84.柱状图中最大的矩形
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans = 0;
heights.insert(heights.begin(), 0);
heights.push_back(0);
stack<int> mono;
mono.push(0);
for (int i = 1; i < heights.size(); i++) {
while (heights[i] < heights[mono.top()]) {
int mid = mono.top(); mono.pop();
int w = i - mono.top() - 1;
int h = heights[mid];
ans = max(ans, w * h);
}
mono.push(i);
}
return ans;
}
};