# 30 Day Challenge Day 22 | Leetcode 85. Maximal Rectangle

## 题解

Hard

class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;

int m = matrix.size();
int n = matrix[0].size();

vector<int> height(n, 0), left(n, 0), right(n, n-1);

int maxArea = 0;

for(int i = 0; i < m; i++) {
int cur_left = 0, cur_right = n-1;

// (1) update height[i] namely histogram
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '1') {
height[j]++;
} else {
height[j] = 0;
}
}

// (2) update left[i]
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '1') {
left[j] = max(left[j], cur_left);
} else {
left[j] = 0; // go back to left most
cur_left = j+1;
}
}

// (3) update right[i]
for(int j = n-1; j >= 0; j--) {
if(matrix[i][j] == '1') {
right[j] = min(right[j], cur_right);
} else {
right[j] = n-1; // go back to right most
cur_right = j-1;
}
}

// update maxArea
for(int j = 0; j < n; j++) {
maxArea = max(maxArea, (right[j]-left[j]+1)*height[j] );
}
}

return maxArea;
}
};



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int r = matrix.size();
if (r == 0) return 0;
int c = matrix[0].size();

// dp[i][j] := max len of all 1s ends with col j at row i.
vector<vector<int>> dp(r, vector<int>(c));

for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
dp[i][j] = (matrix[i][j] == '1') ? (j == 0 ? 1 : dp[i][j - 1] + 1) : 0;

int ans = 0;

for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
int len = INT_MAX;
for (int k = i; k < r; k++) {
len = min(len, dp[k][j]);
if (len == 0) break;
ans = max(len * (k - i + 1), ans);
}
}

return ans;
}
};

posted @ 2020-10-10 05:21  CasperWin  阅读(107)  评论(0编辑  收藏  举报