85. 最大矩形
这道题直接做难度较大,可转换为圆柱图的最大矩形面积的问题,先把这个矩阵转换为
就是每一行对应一个圆柱形图像,然后分别求解最大值即可。
long long max(long long a, long long b) { return a > b ? a : b; } int Histogram_sMax(const vector<char> &data) { stack<int> Stack; long long sMax = 0; int tmp = 0; for (int i = 0; i < data.size(); i++) { if (Stack.empty() || Stack.top() <= data[i]-'0') Stack.push(data[i] - '0'); else { int count = 1; while (!Stack.empty() && Stack.top()>data[i] - '0') { tmp = (count++) * Stack.top(); sMax = max(sMax, tmp); Stack.pop(); } while (count-->0) { Stack.push(data[i] - '0'); } } } // cout << "size : " << Stack.size() << endl; int count = 1; while (!Stack.empty()) { sMax = max(sMax, Stack.top()*count++); Stack.pop(); } return sMax; } int maximalRectangle(vector<vector<char>>& matrix) { if (matrix.empty()) return 0; const int rows = matrix.size(); const int cols = matrix[0].size(); for (int i = 1; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == '1' && matrix[i - 1][j] > 0) matrix[i][j] += matrix[i - 1][j] - '0'; } } int rmax = 0; for (int i = 0; i < rows; i++) { rmax = max(rmax,Histogram_sMax(matrix[i])); } return rmax; }