-
Notifications
You must be signed in to change notification settings - Fork 10
/
maximal-rectangle.cpp
88 lines (77 loc) · 2.58 KB
/
maximal-rectangle.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Time: O(m * n)
// Space: O(n)
// Ascending stack solution.
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.empty() || matrix[0].empty()) {
return 0;
}
int res = 0;
vector<int> height(matrix[0].size(), 0);
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0;
}
res = max(res, largestRectangleArea(height));
}
return res;
}
private:
int largestRectangleArea(const vector<int> &height) {
stack<int> increasing_height;
int max_area = 0;
for (int i = 0; i <= height.size();) {
if (increasing_height.empty() ||
(i < height.size() && height[i] > height[increasing_height.top()])) {
increasing_height.emplace(i);
++i;
} else {
auto h = height[increasing_height.top()];
increasing_height.pop();
auto left = increasing_height.empty() ? -1 : increasing_height.top();
max_area = max(max_area, h * (i - left - 1));
}
}
return max_area;
}
};
// Time: O(m * n)
// Space: O(n)
// DP solution.
class Solution2 {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.empty()) {
return 0;
}
const int m = matrix.size();
const int n = matrix.front().size();
int res = 0;
vector<int> H(n, 0); // Height of all ones rectangle include matrix[i][j].
vector<int> L(n, 0); // Left closed bound of all ones rectangle include matrix[i][j].
vector<int> R(n, n); // Right open bound of all ones rectangle include matrix[i][j].
for (int i = 0; i < m; ++i) {
int left = 0, right = n;
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') {
++H[j]; // Update height.
L[j] = max(L[j], left); // Update left bound.
} else {
left = j + 1;
H[j] = L[j] = 0;
R[j] = n;
}
}
for (int j = n - 1; j >= 0; --j) {
if (matrix[i][j] == '1') {
R[j] = min(R[j], right); // Update right bound.
res = max(res, H[j] * (R[j] - L[j]));
} else {
right = j;
}
}
}
return res;
}
};