jayati

Next Greater Element

Oct 6th, 2023
1,314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7. class Solution
  8. {
  9.     public:
  10.     //Function to find the next greater element for each element of the array.
  11.     vector<long long> nextLargerElement(vector<long long> arr, int n){
  12.         // Your code here
  13.         stack<long long> s;
  14.         vector<long long> ans(n,0);
  15.        
  16.         for(int i=0;i<arr.size();i++)
  17.         {
  18.            
  19.             if(s.empty())
  20.             {
  21.                 s.push(i);
  22.                 continue;
  23.             }
  24.             while(!s.empty() && arr[s.top()]<arr[i])
  25.             {
  26.                 ans[s.top()]=arr[i];
  27.                 s.pop();
  28.             }
  29.             s.push(i);
  30.            
  31.         }
  32.         while(!s.empty())
  33.         {
  34.             ans[s.top()]=-1;
  35.             s.pop();
  36.         }
  37.         return ans;
  38.     }
  39. };
  40.  
  41. //{ Driver Code Starts.
  42.  
  43. int main()
  44. {
  45.     int t;
  46.     cin>>t;
  47.     while(t--)
  48.     {
  49.        
  50.         int n;
  51.         cin>>n;
  52.         vector<long long> arr(n);
  53.         for(int i=0;i<n;i++)
  54.             cin>>arr[i];
  55.        
  56.         Solution obj;
  57.         vector <long long> res = obj.nextLargerElement(arr, n);
  58.         for (long long i : res) cout << i << " ";
  59.         cout<<endl;
  60.     }
  61.     return 0;
  62. }
  63. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment