Second Largest Element
Problem
Read an array. Print the second largest distinct value. If there is no such value (all elements are equal, or there is only one element), print none.
Constraints
- 1 <= n <= 10^5
- -2^31 <= a[i] < 2^31
Examples
Input
5 4 9 1 9 3
Output
4
Solutions
One pass with two variables is enough. Equal values must not count twice, so the second value is always strictly smaller than the largest.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The second largest or none.
* Approach: Track two values.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(int[] a) {
// Step 1: Keep the two largest distinct values. Long.MIN_VALUE means: not found yet.
long largest = Long.MIN_VALUE;
long second = Long.MIN_VALUE;
// Step 2: Check every element once.
for (int value : a) {
if (value > largest) {
// Step 3: A new largest value. The old largest becomes the second.
second = largest;
largest = value;
} else if (value < largest && value > second) {
// Step 4: Smaller than the largest, but bigger than the second.
second = value;
}
}
// Step 5: If the second value was never set, there is no answer.
return second == Long.MIN_VALUE ? "none" : String.valueOf(second);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- What happens when the same maximum appears twice?