-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondLargest.java
More file actions
32 lines (23 loc) · 845 Bytes
/
Copy pathSecondLargest.java
File metadata and controls
32 lines (23 loc) · 845 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
32
package array;
public class SecondLargest {
private static int secondLargestElement(int[] arr) {
if (arr.length < 2) {
return -1;
}
int largestElement = Integer.MIN_VALUE;
int secondLargestElement = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largestElement) {
secondLargestElement = largestElement;
largestElement = arr[i];
} else if (arr[i] > secondLargestElement && arr[i] != largestElement) {
secondLargestElement = arr[i];
}
}
return secondLargestElement;
}
public static void main(String[] args) {
int[] arr = {21, 21, 2, 5, 1, 3, 0, 11, -12, 19, 19, 11, 20, 20, 21};
System.out.println(secondLargestElement(arr));
}
}