Advertisement
29rohitkr

Next Greater Element Approach 1

Feb 22nd, 2023
1,131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1.  
  2.     //Function to find the next greater element for each element of the array.
  3.  
  4.  
  5.     //Function to find the next greater element for each element of the array.
  6.     vector<long long> nextLargerElement(vector<long long> arr, int n){
  7.         // Your code here
  8.         vector<long long> res;
  9.         stack<long long> st;
  10.         int i;
  11.         //st.push(arr[0]);
  12.         for(i=n-1; i>=0 ; i--)
  13.         {
  14.             while( st.empty()==false && st.top()<= arr[i])
  15.                 st.pop();
  16.                
  17.             if( !st.empty() && st.top() > arr[i]){
  18.                 res.push_back(st.top());
  19.             }
  20.             else
  21.                 res.push_back(-1);
  22.                
  23.             st.push(arr[i]);
  24.         }
  25.         reverse(res.begin(), res.end());
  26.         return res;
  27.        
  28.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement