LeetCode 84柱状图中最大的矩形
题目链接:84.柱状图中最大的矩形
//动态规划/双指针
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
//以当前柱子作高,可以获得的最大矩形面积
int size = heights.size();
vector<int> minLeftIndex(size);
vector<int> minRightIndex(size);
//每个柱子 左边第一个小于此柱子的下标
minLeftIndex[0] = -1;
for (int i = 1; i < size; ++i) {
int index = i - 1;
while (index >= 0 && heights[index] >= heights[i]) index = minLeftIndex[index];
minLeftIndex[i] = index;
}
minRightIndex[size - 1] = size;
for (int i = size - 2; i >= 0; --i) {
int index = i + 1;
while (index < size && heights[index] >= heights[i]) index = minRightIndex[index];
minRightIndex[i] = index;
}
int ans = 0;
for (int i = 0; i < size; ++i) {
int count = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1);
if (count > ans) ans = count;
}
return ans;
}
};
//单调栈
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans = 0;
//关键一步 [2,4]末尾加上0才能将4和2作为高的情况全部处理出来
//和一开始在栈中放入-1类似
heights.push_back(0);
//以当前柱子作高,可以获得的最大矩形面积
int size = heights.size();
stack<int> st;
st.push(-1);
//要找柱子两边第一个小于此柱子的柱子
//从栈底到栈顶应该是递增的
for (int i = 0; i < size; ++i) {
while (st.top() != -1 && heights[st.top()] > heights[i]) {
int h = heights[st.top()]; st.pop();
ans = max(ans, (i - st.top() - 1) * h);
}
st.push(i);
}
return ans;
}
};