fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void NGE(int arr[] , int n){
  6.  
  7.  
  8. int res[n];
  9. //starting from reverse to get the right order for each element
  10. res[n-1] = -1;
  11. stack<int> s;
  12. s.push(arr[n-1]);
  13. for(int i =n-2;i>=0;i--){
  14.  
  15. while(!s.empty() && arr[i]>s.top())
  16. s.pop();
  17.  
  18. if(s.empty() )
  19. res[i] = -1;
  20. else
  21. res[i] = s.top();
  22.  
  23. s.push(arr[i]);
  24. }
  25.  
  26. for(int i =0;i<n;i++)
  27. cout<<res[i]<<endl;
  28.  
  29.  
  30. }
  31. int main(){
  32.  
  33.  
  34.  
  35. int n;
  36. cin>>n;
  37. int arr[n];
  38. for(int i =0;i<n;i++){
  39. cin>>arr[i];
  40. }
  41.  
  42. NGE(arr , n);
  43. return 0;
  44. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty