-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxAreaOfHistogram-Stack.cpp
More file actions
75 lines (71 loc) · 1.91 KB
/
MaxAreaOfHistogram-Stack.cpp
File metadata and controls
75 lines (71 loc) · 1.91 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
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
vector<int> nextsmallerright(int a[], int size) {
vector<int>v1;
stack<pair<int,int>>s1;
int pseudoIndex = size;
for(int i=size-1;i>=0;i--) {
if(s1.size() == 0) {
v1.push_back(pseudoIndex);
}
else if(s1.size()>0 && s1.top().first<a[i]) {
v1.push_back(s1.top().second);
} else if(s1.size()>0 && s1.top().first>=a[i]) {
while(s1.size()>0 && s1.top().first>=a[i]) {
s1.pop();
}
if(s1.size()==0) {
v1.push_back(pseudoIndex);
} else {
v1.push_back(s1.top().second);
}
}
s1.push({a[i],i});
}
reverse(v1.begin(),v1.end());
return v1;
}
vector<int> nextsmallerleft(int a[], int size) {
vector<int>v1;
stack<pair<int,int>>s1;
int pseudoIndex = -1;
for(int i=0;i<size;i++) {
if(s1.size() == 0) {
v1.push_back(pseudoIndex);
}
else if(s1.size()>0 && s1.top().first<a[i]) {
v1.push_back(s1.top().second);
} else if(s1.size()>0 && s1.top().first>=a[i]) {
while(s1.size()>0 && s1.top().first>=a[i]) {
s1.pop();
}
if(s1.size()==0) {
v1.push_back(pseudoIndex);
} else {
v1.push_back(s1.top().second);
}
}
s1.push({a[i],i});
}
return v1;
}
int main() {
int n = 7;
int a[n] = {6,2,5,4,5,1,6};
vector<int>v2 = nextsmallerright(a,n);
vector<int>v3 = nextsmallerleft(a,n);
// for(int i=0;i<n;i++) {
// cout<<v2[i]<<" "<<v3[i]<<endl;
// }
int b[n];
for(int i =0;i<n;i++) {
b[i] = v2[i]-v3[i]-1;
}
int ans = INT_MIN;
for(int i=0;i<n;i++) {
// cout<<b[i]<<endl;
ans = max(a[i]*b[i],ans);
}
cout<<ans<<endl;
}