85. 最大矩形(LeetCode)(单调栈思想)
单调栈思想,在基准线上寻找往上连续的1的最大值

class Solution {
public:
int maxv(vector<int>& heights){
int n = heights.size();
vector<int> left(n), right(n);
stack<int> stk;
for(int i = 0; i < n; ++i){
while(stk.size() && heights[stk.top()] >= heights[i]) stk.pop();
if(stk.empty()) left[i] = -1;
else left[i] = stk.top();
stk.push(i);
}
stk = stack<int>();
for(int i = n - 1; i >= 0; --i){
while(stk.size() && heights[stk.top()] >= heights[i]) stk.pop();
if(stk.empty()) right[i] = n;
else right[i] = stk.top();
stk.push(i);
}
int maxv = 0;
for(int i = 0; i < n; ++i) maxv = max(maxv, (right[i] - left[i] - 1) * heights[i]);
return maxv;
}
int maximalRectangle(vector<vector<char>>& matrix) {
int row = matrix.size(), col = matrix[0].size();
vector<vector<int>> h(row, vector<int>(col));
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(matrix[i][j] == '1'){
if(i) h[i][j] = h[i-1][j] + 1;
else h[i][j] = 1;
}
}
}
int res = 0;
for(int i = 0; i < row; ++i) res = max(res, maxv(h[i]));
return res;
}
};

浙公网安备 33010602011771号