-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondLargest.java
More file actions
28 lines (24 loc) · 815 Bytes
/
Copy pathSecondLargest.java
File metadata and controls
28 lines (24 loc) · 815 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
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
if (arr.length < 2) {
System.out.println("Array must contain at least two elements.");
return;
}
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
if (second == Integer.MIN_VALUE) {
System.out.println("No second largest element (all elements might be equal).");
} else {
System.out.println("The second largest element is: " + second);
}
}
}