-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path85-Maximal-Rectangle.cpp
48 lines (43 loc) · 1.16 KB
/
85-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
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> s;
int maxArea = 0;
int i = 0;
while (i < heights.size()) {
if (s.empty() || heights[i] >= heights[s.top()]) {
s.push(i++);
} else {
int tp = s.top();
s.pop();
int width = s.empty() ? i : i - s.top() - 1;
maxArea = max(maxArea, heights[tp] * width);
}
}
while (!s.empty()) {
int tp = s.top();
s.pop();
int width = s.empty() ? i : i - s.top() - 1;
maxArea = max(maxArea, heights[tp] * width);
}
return maxArea;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> heights(cols, 0);
int maxArea = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == '0') {
heights[j] = 0;
} else {
heights[j]++;
}
}
maxArea = max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
};