Find Maximum Element in Java
Problem
The maximum element of an array is the single largest value it contains.
Given an array of integers, find its maximum element.
Java Program
public class MaxInArray {
public static void main(String[] args) {
int[] arr = {4, 17, 9, 42, 8, 23};
int max = arr[0]; // assume the first element is the largest so far
for (int num : arr) {
if (num > max) max = num; // update whenever a bigger value is found
}
System.out.println("Maximum: " + max);
}
}Output
Core Logic
A single pass through the array, keeping track of the biggest value seen so far, is all it takes.
- 1
maxis initialized to the first element of the array,arr[0]. - 2A for-each loop visits every remaining element in turn.
- 3Each element is compared against
maxwithif (num > max). - 4Whenever a larger value is found,
maxis updated to that value. - 5After the full pass,
maxholds the largest element in the array.
[4, 17, 9, 42, 8, 23], max updates to 17 then 42, and stays 42 for the rest of the scan.Key Point: A single pass is enough — no sorting required, so this runs in O(n) time with O(1) extra space.
Why: The array is scanned once from start to end, and only a single max variable is kept regardless of array size.
Key Concepts
Approach 2: Java Streams
import java.util.Arrays;
public class MaxInArrayStream {
public static void main(String[] args) {
int[] arr = {4, 17, 9, 42, 8, 23};
// max() reduces the stream to its largest value, wrapped in an OptionalInt
int max = Arrays.stream(arr).max().getAsInt();
System.out.println("Maximum: " + max);
}
}
Output
Core Logic
Streams already know how to do this — max() reduces the array down to its largest value in one call.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.max()reduces the stream down to the largest value, returning it wrapped in anOptionalInt. - 3
.getAsInt()unwraps theOptionalIntinto a plainint.
Arrays.stream(new int[]{4, 17, 9, 42, 8, 23}).max() reduces the array down to 42.Key Point: OptionalInt is empty if the array is empty, so calling .getAsInt() without checking .isPresent() first would throw — worth remembering before using this on untrusted input.
Why: Arrays.stream().max() still visits every element once internally, and reduces down to a single OptionalInt without allocating any extra storage.
Key Concepts
Interview Questions
What should the starting value be?
The first element. Starting from 0 gives the wrong answer for arrays of negative numbers.
How do you find the maximum with a stream?
Arrays.stream(arr).max().getAsInt(). max() returns an OptionalInt, which is empty for an empty array.