Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Maximum Element

Problem Statement

Write a Java program that implements a method to find the maximum element in an array of integers. The program should return the largest element in the array and test the method with arrays containing positive and negative numbers, including edge cases like single-element arrays and arrays with duplicate maximum values. You can visualize this as searching through a list of exam scores to find the highest score, ensuring the method works whether the scores are positive, negative, or a mix of both.

Input: An array of integers (e.g., arr = [3, -1, 5, 2, -7]). Output: An integer representing the maximum element in the array (e.g., 5 for [3, -1, 5, 2, -7]). Constraints:

  • The array length is between 1 and 10^5.
  • Elements are integers between -10^9 and 10^9.
  • The array is guaranteed to have at least one element. Example:
  • Input: arr = [3, -1, 5, 2, -7]
  • Output: 5
  • Explanation: The maximum element in the array is 5.
  • Input: arr = [-2, -5, -1, -8]
  • Output: -1
  • Explanation: The maximum element in the array is -1.

Pseudocode

FUNCTION findMax(arr)
    IF arr is null OR length of arr equals 0 THEN
        RETURN null
    ENDIF
    SET max to arr[0]
    FOR i from 1 to length of arr - 1
        IF arr[i] > max THEN
            SET max to arr[i]
        ENDIF
    ENDFOR
    RETURN max
ENDFUNCTION

FUNCTION main()
    SET testArrays to arrays of integers
    FOR each array in testArrays
        CALL findMax(array)
        PRINT result
    ENDFOR
ENDFUNCTION

Algorithm Steps

  1. Check if the input array is null or empty. If so, return null (or throw an exception, depending on requirements).
  2. Initialize a variable max to the first element of the array.
  3. Iterate through the array from index 1 to the last index.
  4. For each element, compare it with max. If the element is greater than max, update max to the element’s value.
  5. After the loop, return max as the maximum element.
  6. In the main method, create test arrays with positive and negative numbers and call the findMax method to verify correctness.

Java Implementation

public class MaximumElement {
    // Finds the maximum element in an array
    public Integer findMax(int[] arr) {
        // Check for null or empty array
        if (arr == null || arr.length == 0) {
            return null;
        }
        // Initialize max to first element
        int max = arr[0];
        // Iterate through array to find maximum
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }

    // Main method to test findMax with various arrays
    public static void main(String[] args) {
        MaximumElement maxElement = new MaximumElement();
        
        // Test case 1: Mixed positive and negative numbers
        int[] arr1 = {3, -1, 5, 2, -7};
        System.out.println("Maximum element in arr1: " + maxElement.findMax(arr1));
        
        // Test case 2: All negative numbers
        int[] arr2 = {-2, -5, -1, -8};
        System.out.println("Maximum element in arr2: " + maxElement.findMax(arr2));
        
        // Test case 3: Single element
        int[] arr3 = {42};
        System.out.println("Maximum element in arr3: " + maxElement.findMax(arr3));
        
        // Test case 4: Duplicate maximum values
        int[] arr4 = {4, 4, 3, 4, 2};
        System.out.println("Maximum element in arr4: " + maxElement.findMax(arr4));
        
        // Test case 5: Null array
        int[] arr5 = null;
        System.out.println("Maximum element in arr5: " + maxElement.findMax(arr5));
    }
}

Output

Running the main method produces:

Maximum element in arr1: 5
Maximum element in arr2: -1
Maximum element in arr3: 42
Maximum element in arr4: 4
Maximum element in arr5: null

Explanation:

  • For arr1 = [3, -1, 5, 2, -7], the maximum is 5.
  • For arr2 = [-2, -5, -1, -8], the maximum is -1 (largest among negatives).
  • For arr3 = [42], the maximum is 42 (single element).
  • For arr4 = [4, 4, 3, 4, 2], the maximum is 4 (handles duplicates).
  • For arr5 = null, the method returns null.

How It Works

  • Step 1: The findMax method checks if the array is null or empty. For [3, -1, 5, 2, -7], it proceeds.
  • Step 2: Initialize max = arr[0] = 3.
  • Step 3: Iterate from index 1 to 4:
    • Index 1: arr[1] = -1, -1 < 3, so max remains 3.
    • Index 2: arr[2] = 5, 5 > 3, so max = 5.
    • Index 3: arr[3] = 2, 2 < 5, so max remains 5.
    • Index 4: arr[4] = -7, -7 < 5, so max remains 5.
  • Step 4: Return max = 5.
  • Example Trace: For [3, -1, 5, 2, -7], max updates: 3 → 5, returning 5.
  • Main Method: The main method tests the findMax method with various arrays, including mixed numbers, all negatives, single-element, duplicates, and null, printing the results.

Complexity Analysis Table

OperationTime ComplexitySpace Complexity
IterationO(n)O(1)
Full AlgorithmO(n)O(1)

Note:

  • n is the size of the input array.
  • Time complexity: O(n), as the algorithm iterates through the array once, comparing each element.
  • Space complexity: O(1), as only a single variable (max) is used, regardless of array size.
  • Best, average, and worst cases are O(n), as all elements are processed.

✅ Tip: Initialize the maximum to the first element to handle arrays with negative numbers efficiently. Test with edge cases like single-element arrays, all-negative arrays, and arrays with duplicates to ensure robustness.

⚠ Warning: Ensure the input array is not null or empty to avoid NullPointerException or unexpected behavior. For very large arrays, ensure elements are within the integer range to avoid overflow issues in comparisons.