-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxSizeRectangleOfAllOnes.cpp
More file actions
78 lines (56 loc) · 1.75 KB
/
maxSizeRectangleOfAllOnes.cpp
File metadata and controls
78 lines (56 loc) · 1.75 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <stack>
#include <climits>
using namespace std;
typedef vector< vector<int> > Grid;
int getMaxArea(vector<int> & histogram) {
if (histogram.empty()) return -1;
stack<int> stackOfIndices;
int area = 0;
int maxArea = INT_MIN;
int i;
for (i = 0; i < histogram.size(); ++i) {
//Push as long as building height increases
if (stackOfIndices.empty() || histogram[i] >= histogram[stackOfIndices.top()] ) {
stackOfIndices.push(i);
} else {
//Pop as value is <= histogram[i] and compute area
int topIndex = stackOfIndices.top();
stackOfIndices.pop();
area = stackOfIndices.empty()?histogram[topIndex]*i:histogram[topIndex]*(i-stackOfIndices.top()-1);
maxArea = max(maxArea,area);
}
}
while (!stackOfIndices.empty()) {
int topIndex = stackOfIndices.top();
stackOfIndices.pop();
area = stackOfIndices.empty()?histogram[topIndex]*i:histogram[topIndex]*(i-stackOfIndices.top()-1);
maxArea = max(maxArea,area);
}
return maxArea;
}
int maxSizeRectangle(Grid & g) {
if (g.empty() || g[0].empty()) return -1;
int numCol = g[0].size();
vector<int> result(numCol);
for (int col = 0; col < numCol; ++col)
result[col] =g[0][col];
int val = getMaxArea(result);
for (int row = 1 ; row < g.size(); ++row) {
for (int col = 0; col < numCol; ++col) {
result[col] = (g[row][col] == 0) ? 0 : result[col]+1;
val = std::max(val, getMaxArea(result));
}
}
return val;
}
int main() {
Grid g = { {1,0,0,1,1,1},
{1,0,1,1,0,1},
{0,1,1,1,1,1},
{0,0,1,1,1,1}};
cout<<maxSizeRectangle(g)<<endl;
vector<int> v = {2,2,2,6,1,5,4,2,2,2,2};
cout<<getMaxArea(v)<<endl;
}