-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistogra.cpp
69 lines (68 loc) · 1.88 KB
/
histogra.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
#include<cstdio>
#include<stack>
using namespace std;
int main() {
while(true) {
int n;
long long maxArea = 0;
scanf("%d", &n);
if(n == 0) {
break;
}
bool readNext = true;
stack<long long> stk;
stack<int> idx;
int i;
int height;
for(i=0;i<n;) {
if(readNext) {
scanf("%d", &height);
readNext = false;
}
if(stk.empty() || stk.top() <= height) {
stk.push(height);
idx.push(i);
readNext = true;
++i;
} else {
long long poppedHeight = stk.top();
int poppedIdx = idx.top();
stk.pop();
idx.pop();
// right area
long long area = poppedHeight * (i - poppedIdx);
// left area
int length;
if(!idx.empty()) {
length = poppedIdx - idx.top() - 1;
} else {
length = poppedIdx;
}
long long leftArea = poppedHeight * length;
area += leftArea;
if(area > maxArea) {
maxArea = area;
}
}
}
while(!stk.empty()) {
long long popHeight = stk.top();
int poppedIdx = idx.top();
stk.pop();
idx.pop();
long long ar = popHeight * (i-poppedIdx);
int length;
if(!idx.empty()) {
length = poppedIdx - idx.top() - 1;
} else {
length = poppedIdx;
}
long long lAr = popHeight * length;
ar += lAr;
if(ar > maxArea) {
maxArea = ar;
}
}
printf("%lld\n", maxArea);
}
}