-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path85.maximal-rectangle.cpp
72 lines (69 loc) · 1.87 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* @lc app=leetcode id=85 lang=cpp
*
* [85] Maximal Rectangle
*
* https://leetcode.com/problems/maximal-rectangle/description/
*
* algorithms
* Hard (33.83%)
* Total Accepted: 128.2K
* Total Submissions: 377.3K
* Testcase Example: '[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]'
*
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
* containing only 1's and return its area.
*
* Example:
*
*
* Input:
* [
* ["1","0","1","0","0"],
* ["1","0","1","1","1"],
* ["1","1","1","1","1"],
* ["1","0","0","1","0"]
* ]
* Output: 6
*
*
*/
class Solution {
public:
int maximalRectangle(vector<vector<char>>& mat) {
int n = mat.size();
if(n == 0) return 0;
int m = mat[0].size();
int matrix[n][m+1];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++){
if(mat[i][j] == '0')
matrix[i][j] = 0;
else
matrix[i][j] = (i!=0?matrix[i-1][j]:0) + 1;
}
for(int j=0; j<n; j++)
matrix[j][m] = 0;
// for(int i=0; i<n; i++){
// for(int j=0; j<m+1; j++)
// cout<<matrix[i][j]<<" ";
// cout<<"\n";
// }
int gmax = 0;
for(int r = 0; r<n; r++){
stack<int> st;
int ans = 0;
for(int i=0; i<m+1; i++){
while(!st.empty() && matrix[r][st.top()] >= matrix[r][i]){
int h = matrix[r][st.top()];
st.pop();
ans = max(ans, (i-1 - (st.empty()?-1:st.top()))*h);
}
ans = max(ans, (i - (st.empty()?-1:st.top()))*matrix[r][i]);
st.push(i);
}
gmax = max(gmax, ans);
}
return gmax;
}
};