-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecondHighest.java
36 lines (31 loc) · 1.04 KB
/
SecondHighest.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
package InterviewProblems;
import java.util.Arrays;
public class SecondHighest {
public static void main(String[] args) {
// int[] arr = {11, 4, 3, 8, 11, 4, 11, 9};
//
// int firstMax = Integer.MIN_VALUE;
// int secondMax = Integer.MIN_VALUE;
//
// for (int num : arr) {
// if (num > firstMax) {
// secondMax = firstMax;
// firstMax = num;
// } else if (num > secondMax && num < firstMax) {
// secondMax = num;
// }
// }
//
// System.out.println("Second highest number: " + secondMax);
int[] arr = {11, 4, 3, 8, 11, 4, 11, 9};
int secondMax = Arrays.stream(arr)
.distinct()
.boxed()
.sorted((a, b) -> b - a)
.limit(2)
.skip(1)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Array has less than two distinct elements."));
System.out.println("Second highest number: " + secondMax);
}
}