Leaders in an array

Given an array A of positive integers. Your task is to find the leaders in the array. An element of the array is a leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.









STUDYEVERTHING





// { Driver Code Starts
// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;


 // } Driver Code Ends
   

class Solution{
    //Function to find the leaders in the array.
    public:
    vector<int> leaders(int a[], int n){
         int max =a[n-1];
         vector <int> v;
          v.push_back(a[n-1]);
         for(int i=n-2; i>=0; i--){
             if(a[i]>=max){
                 max = a[i];
                 v.push_back(a[i]);
             }
         }
   
          sort(v.begin(), v.end(), greater<int>());
       return v;
       
    }
};

// { Driver Code Starts.

int main()
{
   long long t;
   cin >> t;//testcases
   while (t--)
   {
       long long n;
       cin >> n;//total size of array
       
        int a[n];
       
        //inserting elements in the array
        for(long long i =0;i<n;i++){
            cin >> a[i];
        }
        Solution obj;
        //calling leaders() function
        vector<int> v = obj.leaders(a, n);
       
        //printing elements of the vector
        for(auto it = v.begin();it!=v.end();it++){
            cout << *it << " ";
        }
       
        cout << endl;

   }
}
  // } Driver Code Ends





Happy Coding 😊.





Post a Comment

If you have furthur QUERIES please let us know

Previous Post Next Post