NEXT GREATER ELEMENT USING STACK
user_6075971
plain_text
3 years ago
872 B
9
Indexable
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector<int> NGE(vector<int> m)
{
vector<int>nge(m.size());
stack<int>s;
for (int i = 0; i < m.size(); i++)
{
while (!s.empty() && m[s.top()] < m[i])
{
nge[s.top()] = i;
s.pop();
}
s.push(i);
}
while (!s.empty())
{
nge[s.top()]=-1;
s.pop();
}
return nge;
}
int main()
{
vector<int> m;
stack<int> s;
int n;
cout << "ENTER THE VECTOR SIZE-->";
cin >> n;
for (int i = 0; i < n; i++)
{
int t;
cin >> t;
m.push_back(t);
}
for (auto value : m)
{
cout << value << " ";
}
cout << endl;
vector<int> v=NGE(m);
for(int i=0;i<n;i++)
{
cout<<m[i]<<"="<<(v[i]==-1? -1:m[v[i]])<<endl;
}
return 0;
}Editor is loading...