int[] a = {3, 8, 5, 8, 2, 7};
int max = a[0];
int second = -1;
for (int i = 1; i < a.length; i++) {
if (a[i] > max) {
second = max;
max = a[i];
} else if (a[i] < max && a[i] > second) {
second = a[i];
}
}
System.out.println(second);What is printed?
- Acheck_circle
7
- B
8
- C
3
- D
5
Explanation
The algorithm tracks the largest strictly less than max. The maximum is 8 (with a duplicate 8), and the second-largest distinct value is 7.