- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathLeadersInArray2.java
56 lines (45 loc) Β· 1.03 KB
/
LeadersInArray2.java
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
packagegfg.Arrays;
importjava.util.Arrays;
publicclassLeadersInArray2 {
publicstaticvoidmain(String[] args) {
int[] arr = { 7, 10, 4, 3, 10, 5, 2 };
int[] arr2 = { 10, 20, 30 };
int[] arr3 = { 30, 20, 10 };
int[] arr4 = { 7, 10, 4, 5, 1, 2 };
System.out.println(Arrays.toString(arr));
leader(arr);
System.out.println();
System.out.println(Arrays.toString(arr2));
leader(arr2);
System.out.println();
System.out.println(Arrays.toString(arr3));
leader(arr3);
System.out.println();
System.out.println(Arrays.toString(arr4));
leader(arr4);
}
/*
* O(n) Time | O(1) Space - this prints leaders from last of array
*/
publicstaticvoidleader(int[] arr) {
intn = arr.length;
intcurrentMax = arr[n - 1];
System.out.print(currentMax + " ");
for (inti = n - 2; i >= 0; i--) {
if (arr[i] > currentMax) {
currentMax = arr[i];
System.out.print(currentMax + " ");
}
}
}
}
/* output:
[7, 10, 4, 3, 10, 5, 2]
2 5 10
[10, 20, 30]
30
[30, 20, 10]
10 20 30
[7, 10, 4, 5, 1, 2]
2 5 10
*/