-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMax_Area_Histogram.cpp
More file actions
109 lines (96 loc) · 2.12 KB
/
Max_Area_Histogram.cpp
File metadata and controls
109 lines (96 loc) · 2.12 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// M A X I M U M A R E A O F H I S T O G R AM
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <climits>
using namespace std;
class Histogram {
public :
void histogramArea(int arr[], int n){
vector <int> vecl;
vector <int> vecr;
vector <int> area;
stack <pair<int,int> > s;
//finding the left nearlest element index
for(int i = 0; i < n; i++){
if(s.empty()){
vecl.push_back(-1);
}
else
if(s.size() > 0 && s.top().first < arr[i]){
vecl.push_back(s.top().second);
}
else
if( s.size() > 0 && s.top().first >= arr[i]){
while( s.size() > 0 && s.top().first >= arr[i] ){
s.pop();
}
if(s.empty()){
vecl.push_back(-1);
}
else{
vecl.push_back(s.top().second);
}
}
s.push({arr[i], i});
}//end of for loop
while (!s.empty()) {
s.pop();
}
//finding the right nearlest element index
for(int i = n-1; i >= 0; i--){
if(s.empty()){
vecr.push_back(n);
}
else
if(s.size() > 0 && s.top().first < arr[i]){
vecr.push_back(s.top().second);
}
else
if(s.size() > 0 && s.top().first >= arr[i]){
while(s.size() > 0 && s.top().first >= arr[i]){
s.pop();
}
if(s.empty()){
vecr.push_back(n);
}
else{
vecr.push_back(s.top().second);
}
}
s.push({arr[i], i});
}//end of Right smallest for loop
reverse(vecr.begin(), vecr.end());
for(auto itl : vecl){
cout<<itl<<" ";
}
cout<<endl;
for(auto itr : vecr){
cout<<itr<<" ";
}
cout<<endl;
int max = INT_MIN;
cout<<"Outside for loop"<<endl;
for(int i = 0; i < n; i++){
area.push_back( ( vecr[i] - vecl[i] -1 ) * arr[i] ) ;
if(area[i] > max){
max = area[i];
}
}
cout<<"Max area is "<<max<<endl;
}//end of method
};
int main(){
cout<<"Enter the size of the array "<<endl;
int n;
cin>>n;
int arr[n];
cout<<"Enter the histogram"<<endl;
for(int i = 0; i < n; i++){
cin>>arr[i];
}
Histogram obj;
obj.histogramArea(arr, n);
return 0;
}