-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array leaders
80 lines (61 loc) · 2.01 KB
/
Array leaders
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//Array leaders
import java.io.*;
import java.util.*;
import java.util.stream.*;
class Array {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter ot = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine().trim());
while(t-- > 0) {
int n = Integer.parseInt(br.readLine().trim());
int arr[] = new int[n];
String inputLine[] = br.readLine().trim().split(" ");
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(inputLine[i]);
}
Solution obj = new Solution();
StringBuffer str = new StringBuffer();
ArrayList<Integer> res = new ArrayList<Integer>();
res = obj.leaders(n, arr);
for(int i = 0; i < res.size(); i++) {
ot.print(res.get(i) + " ");
}
ot.println();
}
ot.close();
}
}
class Solution {
static ArrayList<Integer> leaders(int n, int arr[]) {
//Solution 1
ArrayList<Integer> ans = new ArrayList<>();
for(int i = 0; i < n - 1; i++) {
int maxN = arr[i];
for(int j = i + 1; j < n; j++) {
if(arr[j] > arr[i]) {
maxN = Math.max(maxN, arr[j]);
break;
}
}
if(maxN == arr[i]) {
ans.add(arr[i]);
}
}
ans.add(arr[n - 1]);
return ans;
//Solution 2
ArrayList<Integer> ans = new ArrayList<>();
int left = 0, right = n - 1;
int max = arr[n - 1];
ans.add(max);
for(int i = n - 2; i >= 0; i--) {
if(arr[i] >= max) {
max = arr[i];
ans.add(arr[i]);
}
}
Collections.reverse(ans);
return ans;
}
}