Given an array, Find the Largest element in an array


Example 1:
Input:
 arr[] = {2, 5, 1, 3, 0}  
Output:
 5  
Explanation:
  
5 is the largest element in the array.

Example 2:
Input:
 arr[] = {8, 10, 5, 7, 9}  
Output:
 10  
Explanation:
  
10 is the largest element in the array.

1. Brute Force


Sort the array in ascending order.

Print the element at the (size of the array - 1)th index, which corresponds to the largest element in the array.


import java.util.Arrays;

class Solution {

    // Function to sort the array and return the largest element
    public static int sortArr(int[] arr) {
        // Sort the array in ascending order
        **Arrays.sort(arr);** 
        
        // Return the last element (largest element) after sorting
        return arr[arr.length - 1];
    }
}

public class Main {

    public static void main(String[] args) {
        // Initialize arrays
        int[] arr1 = {2, 5, 1, 3, 0};
        int[] arr2 = {8, 10, 5, 7, 9};
        
        // Find and output the largest element in both arrays
        System.out.println("The Largest element in the array is: " + Solution.sortArr(arr1));
        System.out.println("The Largest element in the array is: " + Solution.sortArr(arr2));
    }
}

1.1 Complexity Analysis


Time Complexity: O(N log N) where N is the size of the array, as we are sorting the array.

Space Complexity: O(1) as we are using a constant


2. Optimal Approach