Find Maximum in Java: Solution, Explanation & Practice
Find the largest element in an array
Problem summary
Find the maximum value in the array [23, 45, 12, 67, 34].
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {23, 45, 12, 67, 34};
// Find and print maximum
// Print: Maximum: <result>
}
}Expected output and test cases
- Find max value
Maximum: 67
Hints
- Start with first element as max
- Compare each element with current max
- Update max if element is larger
Validated solution
Reveal Java solution
public class Main {
static int maximum(int[] values) {
if (values.length == 0) throw new IllegalArgumentException("array is empty");
int best = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] > best) best = values[i];
}
return best;
}
public static void main(String[] args) {
System.out.println("Maximum: " + maximum(new int[] {23, 45, 12, 67, 34}));
}
}How to approach the problem
Use the first value as the current maximum, then replace it only when a larger value appears. This works for all-negative arrays; an arbitrary starting value such as zero does not.
Approach
- Reject an empty array or return an optional result.
- Seed best with the first array value.
- Compare every later value against best.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- All values may be negative.
- Repeated maxima do not need special handling when only the value is requested.
Common mistakes
- Starting best at 0.
- Reading values[0] before deciding what an empty input means.
Follow-up challenge
Return the first index of the maximum too, with a documented tie rule.
Related Arrays exercises
- Practice Declare and Print Array in Java
- Practice Sum of Array in Java
- Practice Calculate Average in Java
Practice all Arrays exercises · Run this idea in the Java compiler