-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathLeadersInAnArray.java
More file actions
31 lines (25 loc) · 811 Bytes
/
LeadersInAnArray.java
File metadata and controls
31 lines (25 loc) · 811 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// using ArrayList
class Solution{
//Function to find the leaders in the array.
static ArrayList<Integer> leaders(int arr[], int n){
ArrayList <Integer> ans = new ArrayList<>();
// edge cases.
if(arr.length==0){
return null;
}
if(arr.length==1){
ans.add(arr[0]);
return null;
}
ans.add(arr[arr.length-1]); // added last elements.
int max = arr [arr.length-1]; // excume last elements is leader elements.
for(int i=arr.length-2; i>=0; i--){
if(arr[i]>=max){
max = arr[i];
ans.add(arr[i]);
}
}
Collections.reverse(ans); // reversing the list.
return ans;
}
}