Finding the maximum and minimum elements in an array is a fundamental task in programming. This task involves iterating through the array while keeping track of the highest and lowest values encountered. This process is essential in various applications, including statistical analysis, data sorting, and algorithm optimization.
To find the maximum and minimum elements in an array in Java, you can use a method that efficiently traverses the array, comparing each element to maintain the current maximum and minimum values. This approach ensures optimal performance, typically with a time complexity of O(n), where n is the number of elements in the array.
Table of Contents
Approach 1: Basic Implementation
public class ApproachOne{
public static int[] findMaxAndMinElement(int[] arr) {
if (arr.length == 0 || arr == null) {
throw new IllegalArgumentException("Aare ohh sambha, array empty hai re!!");
}
int maxElement = arr[0];
int minElement = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxElement)
maxElement = arr[i];
if (arr[i] < minElement)
minElement = arr[i];
}
return new int[] { maxElement, minElement };
}
public static void main(String[] args) {
try {
int[] array = {3, 5, 1, 8, -2, 7, 6, 9};
int[] result = findMaxAndMinElement(array);
System.out.println("The Maximum element is: " + result[0]);
System.out.println("The Minimum element is: " + result[1]);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
The Problem SolutionOutput
The Maximum element is: 9
The Minimum element is: -2
Explanation:
- The method starts by checking if the array is null or empty, throwing an
IllegalArgumentException
if it is. It then initializesmaxElement
andminElement
with the first element of the array. - Then first consider, the first index in the array is your maximum and minimum element.
- Using a
for
loop starting from the second element (index 1), it updatesmaxElement
if the current element is greater andminElement
if the current element is smaller. - Finally, the method returns an array containing the maximum and minimum elements.
Approach 2: Using Utility Method
import java.util.Arrays;
public class ApproachTwo{
public static int[] findMaxAndMinElement(int[] array) {
if (arr.length == 0 || arr == null) {
throw new IllegalArgumentException("Aare ohh sambha, array blank hai re!!");
}
Arrays.sort(array);
return new int[] { array[array.length-1], array[0] };
}
public static void main(String[] args) {
try {
int[] array = {91, -31, -2, 25, 67, 0, 7, -17};
int[] result = findMaxAndMinElement(array);
System.out.println("Maximum element: " + result[0]);
System.out.println("Minimum element: " + result[1]);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
The Problem SolutionOutput
Maximum element: 91
Minimum element: -31
Explanation:
- The method begins by checking if the array is null or empty, and throws an
IllegalArgumentException
if either condition is met. - Using the Arrays class sort() method, arrange all the elements in ascending order.
- If the array is in ascending order then obviously the first element is minimum and the last element is maximum, so extract and return those elements from the array.
Approach 3: Using Java 8
import java.util.Arrays;
public class ApproachThree {
public static int[] findMaxAndMinElement(int[] arr) {
if (arr.length == 0 || arr == null) {
throw new IllegalArgumentException("Aare halkat, eh Array toh Empty hai re.");
}
int maximum = Arrays.stream(arr).max().getAsInt();
int minimum = Arrays.stream(arr).min().getAsInt();
return new int[] { maximum, minimum };
}
public static void main(String[] args) {
try {
int[] array = {102, -592, 621, 79, -442, -36, 239, 50};
int[] result = findMaxAndMinElement(array);
System.out.println("Maximum element: " + result[0]);
System.out.println("Minimum element: " + result[1]);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
The Problem SolutionOutput
Maximum element: 621
Minimum element: -592
Explanation:
- I have successfully thrown an empty array exception, if and only if the given array is blank.
- Get the maximum and minimum from the array by converting the array to a stream and then using the inbuilt methods max() and min().
- The return type of max() and min() is OptionalInt, that’s why I have used getAsInt().
- You may use the variable as ‘OptionalInt’ instead of ‘int’, I have used ‘int’ because, at the first line, I have already thrown an IllegalArgumentException exception if the array is blank. so after that, if it is coming to line no 10 then no need to use optional, here the Array is not blank.
- Finally, return the maximum and minimum element in the form of an array.