Leaders in an array

 

nput: arr[] = [16, 17, 4, 3, 5, 2]
Output: [17 5 2]
Explanation: 17 is greater than all the elements to its right i.e., [4, 3, 5, 2], therefore 17 is a leader. 5 is greater than all the elements to its right i.e., [2], therefore 5 is a leader. 2 has no element to its right, therefore 2 is a leader.

Input: arr[] = [1, 2, 3, 4, 5, 2]
Output: [5 2]
Explanation: 5 is greater than all the elements to its right i.e., [2], therefore 5 is a leader. 2 has no element to its right, therefore 2 is a leader.

class gfg{

    public ArrayList<Integer> leader(int arr[]){

            List<Integer> res =  new ArrayList<>();

            int n = arr.length; 

            int maxEle = arr[n-1]; 

             res.add(maxEle);

            for(int i = n-2;i>=0;i++){

                    if(arr[i] >= maxEle){

                            maxEle = arr[i];

                            res.add(maxEle);

                    }

            }

            return Collections.reverse(res); 

Comments

Popular Posts