AmazonAlgorithmsEasy

Find the maximum element in an array

ArrayAlgorithmsSearch

Question

Write a function to find the maximum element in an array.

Answer

Simple Approach:

public int findMax(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;
}

Using Streams (Java 8+):

public int findMax(int[] arr) {
    return Arrays.stream(arr).max().orElseThrow();
}

Explanation

**Time Complexity:** O(n) - must check every element **Space Complexity:** O(1) - only using constant extra space This is a fundamental algorithm that demonstrates linear search.