-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecondLargest.java
More file actions
29 lines (25 loc) · 991 Bytes
/
secondLargest.java
File metadata and controls
29 lines (25 loc) · 991 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
class Solution {
public int getSecondLargest(int[] arr) {
int n = arr.length;
// Edge case: If the array has less than 2 elements
if (n < 2) {
return -1;
}
// Initialize variables for the largest and second-largest
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
// Traverse the array to find the largest and second-largest elements
for (int num : arr) {
if (num > largest) {
// Update secondLargest before updating largest
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num < largest) {
// Update secondLargest if num is between largest and secondLargest
secondLargest = num;
}
}
// If no second largest element was found, return -1
return (secondLargest == Integer.MIN_VALUE) ? -1 : secondLargest;
}
}