This is the extension of Largest Rectangle in Histogram. We can just project 2D matrix to 1D array and compute it line by line.
1 class Solution { 2 public: 3 int maximalRectangle(vector<vector<char> > &matrix) { 4 if (matrix.size() == 0) return 0; 5 int n = matrix.size(), m = matrix[0].size(), result = 0; 6 vector<int> height(m, 0), left(m), right(m); 7 for (int i = 0; i < n; i++) { 8 for (int j = 0; j < m; j++) { 9 if (matrix[i][j] == ‘1‘) height[j]++; 10 else height[j] = 0; 11 } 12 for (int j = 0; j < m; j++) { 13 left[j] = j; 14 while (left[j] > 0 && height[j] <= height[left[j]-1]) left[j] = left[left[j]-1]; 15 } 16 for (int j = m-1; j >= 0; j--) { 17 right[j] = j; 18 while (right[j] < m-1 && height[j] <= height[right[j]+1]) right[j] = right[right[j]+1]; 19 } 20 for (int j = 0; j < m; j++) { 21 result = max(result, height[j]*(right[j] - left[j] + 1)); 22 } 23 } 24 return result; 25 } 26 };
时间: 2024-12-15 00:24:56