-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextGreaterElement.cpp
More file actions
46 lines (40 loc) · 1015 Bytes
/
nextGreaterElement.cpp
File metadata and controls
46 lines (40 loc) · 1015 Bytes
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
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find the next greater element for each element of the array.
vector<long long> nextLargerElement(vector<long long> arr, int n){
stack<long long> s;
vector<long long> res(n);
for(int i = n - 1; i>=0; i--) {
if(!s.empty()) {
while (!s.empty() && s.top() <= arr[i]) s.pop();
}
res[i] = s.empty() ? -1 : s.top();
s.push(arr[i]);
}
return res;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<long long> arr(n);
for(int i=0;i<n;i++)
cin>>arr[i];
Solution obj;
vector <long long> res = obj.nextLargerElement(arr, n);
for (long long i : res) cout << i << " ";
cout<<endl;
}
return 0;
} // } Driver Code Ends