Skip to main content

Posts

Showing posts with the label Next Larger Element

Next Larger Element

Task: Given an array of N distinct elements, Find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, print -1. Example: Input: 1 4 1 3 2 4 Output: 3 4 4 -1 Here is the Code: Program in C++:   #include<iostream> #include<bits/stdc++.h> using namespace std; int nextLargerElement(int n,long long *a) {     stack<long long> st;     for(int i=n-1;i>=0;i--)     {         while(st.empty()==false&&st.top()<a[i])         {             st.pop();         }         long long t = a[i];         if(st.empty())         {             a[i]=-1;         }         else         {             a[i]=st.top();         }         st.push(t);     }     for(int i=0;i<n;i++)     {         cout<<a[i]<<" ";     } } int main()  { int t; cin>>t; while(t--) {     int n;     cin>>n;     long long a[n];     for(int i=0;i<n;i++)     {         cin>>a[i];