单调栈
#include <iostream>
#include <vector>
#include <stack>
int MaxMatrixArea(const std::vector<int>& line) {
if (line.empty()) {
return 0;
}
std::stack<int> st;
int maxArea = 0;
for (int i = 0; i < line.size(); i++) {
while (!st.empty() && line[st.top()] <= line[i]) {
int t = st.top();
int area = (i - t) * line[t];
if (area > maxArea) {
maxArea = area;
}
st.pop();
}
st.push(i);
}
int n = line.size();
while (!st.empty()) {
int t = st.top();
int area = (n - t) * line[t];
if (area > maxArea) {
maxArea = area;
}
st.pop();
}
return maxArea;
}
int MaxSubMatrix(const std::vector<std::vector<int>>& mat) {
if (mat.empty()) {
return 0;
}
int H = mat.size();
int L = mat[0].size();
std::vector<int> heigh(mat[0].size(), 0);
for (int j = 0; j < L; ++j) {
heigh[j] = mat[0][j];
}
int maxSize = MaxMatrixArea(heigh);
for (int i = 1; i < H; ++i) {
for (int j = 0; j < L; ++j) {
heigh[j] = (mat[i][j] == 0) ? 0 : heigh[j] + 1;
}
int size = MaxMatrixArea(heigh);
if (size > maxSize) {
maxSize = size;
}
}
return maxSize;
}
int main() {
std::vector<int> line {3, 2, 3, 0};
int res = MaxMatrixArea(line);
std::cout << "result = " << res << std::endl;
std::vector<std::vector<int>> mat = {
{1, 0, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 0}};
res = MaxSubMatrix(mat);
std::cout << "max matrix area = " << res << std::endl;
return 0;
}
参考资料
- https://blog.csdn.net/roufoo/article/details/78569554
- https://blog.csdn.net/yutianzuijin/article/details/52072427
- https://www.cnblogs.com/grandyang/p/8887985.html
- https://oi-wiki.org/ds/monotonous-stack/