easyArray Basics (1D)
Largest Element in an Array
Find the largest value in a nonempty integer array.
Work through the cases
3 examplesInput notation
One line of space-separated integers.Expected result
The largest value.Case 1
Input
-4 8 3 1
Expected output
8
Case 2
Input
-9 -2 -7
Expected output
-2
Case 3
Input
0
Expected output
0
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.
Initialize with the first value so negative-only arrays work. Time: O(n). Extra space: O(1), excluding the input array.
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 best = a[0]; for (long v : a) best = Math.max(best, v); System.out.println(best);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.