Skip to content

Commit aeca261

Browse files
Added solution
1 parent 93ef0f4 commit aeca261

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

amazon/nge_in_same_order.cpp

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
void nge(const vector<int> &v){
5+
if(v.size() == 0) return;
6+
7+
int next;
8+
stack<int> s;
9+
s.push(v[0]);
10+
11+
for(int i=1; i<v.size();i++){
12+
next = v[i];
13+
if(s.empty()){ //corner case
14+
s.push(next);
15+
continue;
16+
}
17+
18+
while(!s.empty() && next > s.top()){
19+
cout<<s.top()<<" "<<next<<"\n"; //next is nge for all eles in stack
20+
s.pop();
21+
}
22+
s.push(next);
23+
}
24+
25+
while(!s.empty()){
26+
cout<<s.top()<<" "<<-1<<"\n";
27+
s.pop();
28+
}
29+
}
30+
31+
void ngeSameOrder(const vector<int> &v){
32+
if(v.size() == 0) return;
33+
stack<int> s;
34+
vector<int> res(v.size());
35+
36+
for(int i = v.size()-1; i>=0; i--){
37+
int next = v[i];
38+
39+
while(!s.empty() && s.top() <= next)
40+
s.pop();
41+
42+
if(s.empty())
43+
res[i] = -1;
44+
else
45+
res[i] = s.top();
46+
s.push(v[i]);
47+
}
48+
for(int i=0; i<res.size();i++){
49+
cout<<v[i]<<" "<<res[i]<<"\n";
50+
}
51+
52+
}
53+
54+
int main(){
55+
int n;
56+
cin>>n;
57+
vector<int> v(n);
58+
for(int i=0; i<n; i++)
59+
cin>>v[i];
60+
//nge logic
61+
//nge(v);
62+
ngeSameOrder(v);
63+
return 0;
64+
}

0 commit comments

Comments
 (0)