forked from gitHub1akash/java_tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNGR.cpp
56 lines (42 loc) · 1008 Bytes
/
NGR.cpp
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
// Nearest Greatest Right (NGR)
#include<bits/stdc++.h>
using namespace std;
void fun_stack(int A[],int x);
int main()
{
int i,size=5,arr[5];
cout<<"\nEnter the Array\n";
for(i=0;i<size;i++)
cin>>arr[i];
fun_stack(arr,size);
return 0;
}
void fun_stack(int arr[],int n)
{
vector<int>v;
stack<int>s;
for(int i=n-1;i>=0;i--)
{
if(s.size()==0)
v.push_back(-1);
else if (s.size()>0 && s.top()>arr[i])
v.push_back(s.top());
else if (s.size()>0 && s.top()<=arr[i])
{
while(s.size()>0 && s.top()<=arr[i])
s.pop();
if(s.size()==0)
v.push_back(-1);
else
v.push_back(s.top());
}
s.push(arr[i]);
}
reverse(v.begin(),v.end());
cout<<"\nArray is\n";
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<"\nNearest Greatest Element\n";
for(int i=0;i<n;i++)
cout<<v[i]<<" ";
}