-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathNearestGreaterElementFromRight.cpp
More file actions
53 lines (49 loc) · 1.05 KB
/
Copy pathNearestGreaterElementFromRight.cpp
File metadata and controls
53 lines (49 loc) · 1.05 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
#include <bits/stdc++.h>
using namespace std;
// Next Greater Right Element
vector<int> solve(vector<int> a)
{
// output vector
vector<int> ans;
stack<int> s;
int n = a.size();
// from back side
for(int i=n-1;i>=0;i--){
// base case
if(s.size()==0){
ans.push_back(-1);
}
else if(s.size()>0 && a[i]<s.top()){
ans.push_back(s.top());
}
else if(s.size()>0 && a[i]>=s.top()){
while(s.size()>0 && a[i]>=s.top()){
s.pop();
}
if(s.size()==0){
ans.push_back(-1);
}
else{
ans.push_back(s.top());
}
}
s.push(a[i]);
}
// reverse the array bcz element store from back side
reverse(ans.begin(),ans.end());
return ans;
}
int main(){
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>v[i];
}
// print the output
vector<int> ans = solve(v);
for(int i=0;i<n;i++){
cout<<ans[i]<<" ";
}
return 0;
}