Java Array Program · A01
Find the Largest Element in an Array in Java
Scan the array once and remember the biggest value seen so far. The two traps are starting from the wrong value and forgetting the empty array.
Problem Statement
Write a method that returns the largest value in an int array. The array can contain negative numbers and duplicates.
An empty array has no largest element, so the method throws an IllegalArgumentException in that case.
Input/Output Examples
[12, -5, 48, 7]Output48Explanation: 48 is greater than every other element.[-8, -3, -15]Output-3Explanation: -3 is the largest because it is closest to zero.[42]Output42Explanation: the only element is also the largest.Visual Explanation
[12, -5, 48, 7]: max starts at the first element and changes only when a bigger value appears (purple).Every element is compared with the current max exactly once. Starting from arr[0] instead of 0 is what makes the method correct for arrays in which every value is negative.
Approaches
Both approaches visit each element once. One writes the loop by hand; the other uses IntStream.max().
Approach 1: Single Loop (Recommended)
Idea: start with the first element and replace max whenever a bigger element is found.
- Throw an exception if the array is empty.
- Set
max = arr[0]. - For every later element, if it is greater than
max, store it inmax. - Return
max.
Time: O(n) · Space: O(1).
Approach 2: IntStream.max()
Idea: let Arrays.stream(arr).max() find the maximum; it returns an OptionalInt that is empty for an empty array.
- Create an
IntStreamwithArrays.stream(arr). - Call
max()to get anOptionalInt. - Use
orElseThrow()to return the value or throw for an empty array.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Single Loop (Recommended)
The loop starts at index 1 because arr[0] is already the starting value. The empty check runs first, so arr[0] is always safe.
import java.util.Arrays;
public class LargestLoop {
// Starts from the first element, so all-negative arrays work too
static int findLargest(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("array is empty");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
public static void main(String[] args) {
int[][] inputs = {{12, -5, 48, 7}, {-8, -3, -15}, {42}, {}};
for (int[] arr : inputs) {
try {
System.out.println(Arrays.toString(arr) + " -> " + findLargest(arr));
} catch (IllegalArgumentException e) {
System.out.println(Arrays.toString(arr) + " -> " + e.getMessage());
}
}
}
}
[12, -5, 48, 7] -> 48 [-8, -3, -15] -> -3 [42] -> 42 [] -> array is empty
Time complexity: O(n) · Space complexity: O(1).
Approach 2: IntStream.max()
One expression with no boxing, because IntStream works with primitive int values.
import java.util.Arrays;
public class LargestStream {
// IntStream.max() returns an OptionalInt, which is empty for an empty array
static int findLargest(int[] arr) {
return Arrays.stream(arr)
.max()
.orElseThrow(() -> new IllegalArgumentException("array is empty"));
}
public static void main(String[] args) {
int[][] inputs = {{12, -5, 48, 7}, {-8, -3, -15}, {42}, {}};
for (int[] arr : inputs) {
try {
System.out.println(Arrays.toString(arr) + " -> " + findLargest(arr));
} catch (IllegalArgumentException e) {
System.out.println(Arrays.toString(arr) + " -> " + e.getMessage());
}
}
}
}
[12, -5, 48, 7] -> 48 [-8, -3, -15] -> -3 [42] -> 42 [] -> array is empty
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Single Loop | O(n) | O(1) |
| IntStream.max() | O(n) | O(1) |
Here n is the number of elements. Each element is compared once, and only one extra variable is needed, so both approaches use O(1) auxiliary space.
Interview Tips and Recommended Approach
- Do not start with
max = 0. For[-8, -3, -15]it would return0, which is not even in the array. - Say what happens for an empty array. Throwing an exception, returning
Integer.MIN_VALUEor returning anOptionalIntare all valid, but you must choose one. - Avoid sorting.
Arrays.sort()followed by the last element works, but it costsO(n log n)and changes the input. - Know the follow-ups: the smallest element, the second largest and the index of the maximum all use the same single-pass idea.
Recommended Approach: Single Loop
Why: it reads the array once, needs no extra memory and handles negative numbers because it starts from a real element. Every step is visible, which is what an interviewer wants to see.