-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNext greater element.cpp
75 lines (61 loc) · 1023 Bytes
/
Next greater element.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//****** SIMPLE METHOD ******
/*#include<iostream>
using namespace std;
void NGE(int arr[],int n)
{
int next,i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
next=-1;
if(arr[i]<arr[j])
{
next = arr[j];
break;
}
}
cout<<arr[i]<<"--"<<next<<endl;
}
}
int main()
{
int arr[]={11,45,65,21};
int n =sizeof(arr)/sizeof(arr[0]);
NGE(arr,n);
return 0;
}*/
//******** USING STACK ********
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void NGE(int arr[], int n)
{
stack<int> s;
s.push(arr[0]);
for(int i=1;i<n;i++)
{
if(s.empty())
{
s.push(arr[i]);
continue;
}
while (s.empty()==false && s.top()<arr[i]){
cout<<s.top() << "-->"<<arr[i]<<endl;
s.pop();
}
s.push(arr[i]);
}
while (s.empty()==false)
{
cout<<s.top()<<"-->"<<-1<<endl;
s.pop();
}
}
int main()
{
int arr[]= {11,13,21,3};
int n = sizeof(arr) / sizeof(arr[0]);
NGE(arr,n);
return 0;
}