-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHISTOGRAM.cpp
More file actions
55 lines (51 loc) · 1.13 KB
/
Copy pathHISTOGRAM.cpp
File metadata and controls
55 lines (51 loc) · 1.13 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
#include<iostream>
#include<stack>
using namespace std;
int main() {
int n;
cin>>n;
long arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
stack<int> s;
s.push(0);
long area=0;
for(int i=1;i<n;i++){
//Current element is smaller or equal:
while(!s.empty() && arr[s.top()]>=arr[i]){
//Pop element from stack:
int t=s.top();
s.pop();
//After poping:
//a. Stack becomes empty: all elements on it's left are larger to it:
if(s.empty()){
area=max(area,arr[t]*i);
}
//b. Stack is not empty: current top of stack is smaller to it:
else{
area=max(area,arr[t]*(i-s.top()-1));
}
}
//Push index of current:
s.push(i);
}
//If stack still contains some element: When the last element was larger than the top of stack:
while(!s.empty()){
//Pop element from stack:
int t=s.top();
s.pop();
//After poping:
//a. Stack becomes empty: all elements on it's left are larger to it:
if(s.empty()){
//changes
area=max(area,arr[t]*n);
}
//b. Stack is not empty: current top of stack is smaller to it:
else{
//Changes:
area=max(area,arr[t]*(n-s.top()-1));
}
}
cout<<area;
return 0;
}