-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_STOII_0040_maximalRectangle.cc
More file actions
60 lines (57 loc) · 1.26 KB
/
Problem_STOII_0040_maximalRectangle.cc
File metadata and controls
60 lines (57 loc) · 1.26 KB
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
#include <iostream>
#include <vector>
using namespace std;
// seem as leetcode 0085
// https://leetcode-cn.com/problems/maximal-rectangle/
// see at Problem_0085_maximalRectangle.cc
class Solution
{
public:
int maxLine(vector<int> &arr)
{
int n = arr.size();
vector<int> stack;
int ans = 0;
for (int i = 0; i < n; i++)
{
while (!stack.empty() && arr[stack.back()] >= arr[i])
{
int j = stack.back();
stack.pop_back();
int k = stack.empty() ? -1 : stack.back();
int area = (i - k - 1) * arr[j];
ans = std::max(ans, area);
}
stack.push_back(i);
}
while (!stack.empty())
{
int j = stack.back();
stack.pop_back();
int k = stack.empty() ? -1 : stack.back();
int area = (n - k - 1) * arr[j];
ans = std::max(ans, area);
}
return ans;
}
int maximalRectangle(vector<string> &matrix)
{
if (matrix.size() == 0)
{
return 0;
}
int n = matrix.size();
int m = matrix[0].size();
vector<int> arr(m);
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[j] += matrix[i][j] == '1' ? 1 : -arr[j];
}
ans = std::max(ans, maxLine(arr));
}
return ans;
}
};