-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leaders In Array
43 lines (36 loc) · 1.23 KB
/
Leaders In Array
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
32
33
34
35
36
37
38
39
40
41
42
43
//Given an array A of positive integers. Your task is to find the leaders in the array.
//Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader.
static ArrayList<Integer> leaders(int arr[], int n){
// Your code here
/******************
* You just need to complete this
* function and return the vector
* containing the leaders.
* ***************/
// Approach 1 using Stack
ArrayList<Integer>ans=new ArrayList<>();
// Stack<Integer>st=new Stack<>();
// int count=0;
// for(int i=arr.length-1;i>=0;i--){
// while(st.size()>0 && arr[i]>=st.peek()){
// st.pop();
// }if(st.size()==0){
// ans.add(arr[i]);
// }
// st.push(arr[i]);
// }
//Approach 2 using Arrays
int max = Integer.MIN_VALUE;
for(int i=n-1;i>=0;i--){
if(arr[i]>=max){
max=arr[i];
ans.add(max);
}
}
ArrayList<Integer> temp = new ArrayList<>();
while(ans.size()>0){
int t = ans.remove(ans.size()-1);
temp.add(t);
}
return temp;
}