-
Notifications
You must be signed in to change notification settings - Fork 0
/
042_Maximum_size_rectangle.cpp
73 lines (65 loc) · 1.6 KB
/
042_Maximum_size_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
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
// } Driver Code Ends
/*You are required to complete this method*/
int maxHist(int hist[], int m){
int i = 0, curr_area,max_area=0, top_idx;
stack<int> s;
while (i < m){
if (s.empty() or hist[s.top()] < hist[i]){
s.push(i);
i++;
}
else{
top_idx = s.top();
s.pop();
if (s.empty())
curr_area = hist[top_idx] * i;
else
curr_area = hist[top_idx] * (i - 1 - s.top());
max_area = max(max_area,curr_area);
}
}
while(!s.empty()){
top_idx = s.top();
s.pop();
if (s.empty())
curr_area = hist[top_idx] * i;
else
curr_area = hist[top_idx] * (i - 1 - s.top());
max_area = max(max_area,curr_area);
}
return max_area;
}
class Solution{
public:
int maxArea(int M[MAX][MAX], int n, int m) {
int result = maxHist(M[0], m);
for (int i = 1; i < n; i++){
for(int j = 0; j < m; j++){
if (M[i][j])
M[i][j] += M[i-1][j];
}
result = max(result, maxHist(M[i],m));
}
return result;
}
};
// { Driver Code Starts.
int main() {
int T;
cin >> T;
int M[MAX][MAX];
while (T--) {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> M[i][j];
}
}
Solution obj;
cout << obj.maxArea(M, n, m) << endl;
}
}