easyArray Basics (1D)
Second Largest Element in an Array
Find the second largest distinct value in an array. If fewer than two distinct values exist, print none.
Work through the cases
3 examplesInput notation
One nonempty line of space-separated integers.Expected result
The second largest distinct value, or none.Case 1
Input
7 7 3 1
Expected output
3
Case 2
Input
4 4
Expected output
none
Case 3
Input
-5 -2 -9
Expected output
-5
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Maintain the greatest and second-greatest distinct values. Ignore duplicates of the maximum. Time: O(n). Extra space: O(1), excluding input.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
Long first = null, second = null; for (long v : a) { if (first == null || v > first) { second = first; first = v; } else if (v != first && (second == null || v > second)) second = v; } System.out.println(second == null ? "none" : second);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.