84.柱状图中最大的矩形
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
heights.insert(heights.begin(), 0); // 数组头部加入元素0
heights.push_back(0); // 数组尾部加入元素0
st.push(0);
int result = 0;
for (int i = 1; i < heights.size(); i++) {
while (heights[i] < heights[st.top()]) {
int mid = st.top();
st.pop();
int w = i - st.top() - 1;
int h = heights[mid];
result = max(result, w * h);
}
st.push(i);
}
return result;
}
};
该代码实现了一个算法,用于找出柱状图中最大的矩形面积。它使用了栈数据结构,通过遍历柱状图的高度,并在遇到比栈顶元素高度小的情况时,计算当前矩形的宽度和高度,更新最大面积。最后返回结果。
293

被折叠的 条评论
为什么被折叠?



