-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistogram.cpp
More file actions
57 lines (43 loc) · 1019 Bytes
/
histogram.cpp
File metadata and controls
57 lines (43 loc) · 1019 Bytes
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
/*
Histogram problem.
Given N length Histogram. Find the max area rectangle that can be formed.
Time: O(n)
Space: O(n)
*/
struct histogram{
vector < LL > h;
stack < LL > Stack;
LL MaxArea;
histogram(){
MaxArea = 0;
}
void take(LL a){ h.pb(a); }
LL CalculateMaxArea(){
MaxArea = 0;
for(LL i = 0 ; i<sz(h) ; i++){
if( Stack.empty() || h[Stack.top()]<=h[i] ) Stack.push(i);
else{
while( !Stack.empty() && ( h[Stack.top()] > h[i]) ){
LL minLen = h[Stack.top()]; Stack.pop();
LL area;
if( Stack.empty() ) area = minLen*i;
else area = minLen*(i - Stack.top() - 1);
MaxArea = max(MaxArea , area);
}
Stack.push(i);
}
DEBUG(h[i]);
}
while(!Stack.empty()){
LL minLen = h[Stack.top()]; Stack.pop();
LL area;
if( Stack.empty() ) area = minLen*sz(h);
else area = minLen*(sz(h) - Stack.top() - 1);
MaxArea = max(MaxArea , area);
}
return MaxArea;
}
void clear(){
h.clear();
}
};