top of page

Keep Reading !

You can also checkout more topics like...

peep-101_edited.png
EXPLORE COURSES (6).png
EXPLORE COURSES (9).png
EXPLORE COURSES (7)_edited.jpg

Leaders in an array

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

Example 01:

Input:
n = 6
Ar[] = {8,5,9,1,2,3}
0,1,5,2}
Output: 17 5 2

Example 2:

Input:
n = 6
Arr[] = {8,5,9,1,2,3}
Output: 9, 3

Your Task: Find the highest values compared to their right most elements Time Complexity: O(n) Auxiliary Space: O(n)

static ArrayList<Integer> leaders(int arr[], int n){
// Your code here
ArrayList<Integer> list = new ArrayList<>();
int maxElem = arr[n-1];
 list.add(maxElem);

for(int i = n-2; i>=0; i--)
{
        
  if(arr[i]>=maxElem ){
   maxElem = arr[i];
  list.add(maxElem);
               }

}
Collections.reverse(list);
 return list;

}
9 views0 comments

Recent Posts

See All

コメント


bottom of page