Deepak Pandey

Program to Find Largest Element in an Array

Problem Statement

You are given an array arr[] of size N, where N represents the number of elements in the array. The task is to write a program to find and determine the largest element within this array.

Examples

Example 1:

Input: arr[] = {3, 5, 4}
Output: 5
Explanation: Among 3, 5 and 4, 5 is the largest element. 

Example 2:

Input: arr[] = {50, 11, 33, 50, 20}
Output: 50
Explanation: Among all the elements, 50 is the largest element.

Example 3:

Input: arr[] = {-10, -20, 0, -1, -2}
Output: 0
Explanation: Among all the elements, 0 is the largest element. 

Example Explanation

In above all the examples, we are finding the largest element from the array. The array might contain a negative element.

Constraints

You are provided with an array arr[] of size N. Your objective is to identify the largest element within this given array.

0 ≤ N ≤ 10^6
-10^3 ≤ arr[i] ≤ 10^6
Array may contain duplicate elements. 

Approach 1 – Iterative Approach

The iterative approach involves traversing through the array and keeping track of the largest element encountered so far. As you iterate through each element, compare it with the current largest element. If the current element is greater than the current largest element, update the largest element to the current element.

Algorithm:

  1. Initialize a variable max_element with a value of negative infinity. This will serve as the placeholder for the largest element.
  2. Iterate through each element num in the array arr[]:
    • If num is greater than max_element, update max_element to the value of num.
  3. After iterating through the entire array, the variable max_element will hold the largest element.

Code Implementation

Below is the implementation of the above approach in different programming languages:

C Programming Language:

#include <stdio.h>

int findLargestElement(int arr[], int N) {
    int maxElement = INT_MIN; // Initialize with the smallest possible value

    for (int i = 0; i < N; i++) {
        if (arr[i] > maxElement) {
            maxElement = arr[i];
        }
    }

    return maxElement;
}

int main() {
    int N;
    printf("Enter the size of the array: ");
    scanf("%d", &N);

    int arr[N];
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < N; i++) {
        scanf("%d", &arr[i]);
    }

    int largest = findLargestElement(arr, N);
    printf("The largest element in the array is: %d\n", largest);

    return 0;
}

Output:

Enter the size of the array: 5
Enter the elements of the array:
12 45 9 33 7
The largest element in the array is: 45

Explanation:

  • The function findLargestElement takes an array arr and its size N as parameters and returns the largest element in the array.
  • We start by initializing maxElement to INT_MIN, which represents the smallest possible integer value.
  • The for loop iterates through each element in the array. For each element, it checks if the element is greater than the current maxElement. If it is, the value of maxElement is updated with the current element.
  • After iterating through the entire array, the function returns the maxElement, which will be the largest value encountered.
  • In the main function, we read the size of the array and its elements from the user. Then, we call the findLargestElement function to obtain the largest element and print it.

C++ Programming Language:

#include <iostream>
#include <climits> // For INT_MIN

int findLargestElement(int arr[], int N) {
    int maxElement = INT_MIN; // Initialize with the smallest possible value

    for (int i = 0; i < N; i++) {
        if (arr[i] > maxElement) {
            maxElement = arr[i];
        }
    }

    return maxElement;
}

int main() {
    int N;
    std::cout << "Enter the size of the array: ";
    std::cin >> N;

    int arr[N];
    std::cout << "Enter the elements of the array:" << std::endl;
    for (int i = 0; i < N; i++) {
        std::cin >> arr[i];
    }

    int largest = findLargestElement(arr, N);
    std::cout << "The largest element in the array is: " << largest << std::endl;

    return 0;
}

Output:

Enter the size of the array: 4
Enter the elements of the array:
5 20 7 15
The largest element in the array is: 20

Explanation:

  • After iterating through the entire array, the function returns the maxElement, which will be the largest value encountered.
  • In the main function, we read the size of the array and its elements using std::cin. Then, we call the findLargestElement function to obtain the largest element and print it using std::cout.

JAVA Programming Language:

import java.util.Scanner;

public class FindLargestElement {
    public static int findLargestElement(int[] arr) {
        int maxElement = Integer.MIN_VALUE; // Initialize with the smallest possible value

        for (int num : arr) {
            if (num > maxElement) {
                maxElement = num;
            }
        }

        return maxElement;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int N = scanner.nextInt();

        int[] arr = new int[N];
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < N; i++) {
            arr[i] = scanner.nextInt();
        }

        int largest = findLargestElement(arr);
        System.out.println("The largest element in the array is: " + largest);

        scanner.close();
    }
}

Output:

Enter the size of the array: 6
Enter the elements of the array:
8 16 3 10 25 2
The largest element in the array is: 25

Explanation:

  • After iterating through the entire array, the method returns the maxElement, which will be the largest value encountered.
  • In the main method, we use a Scanner to read the size of the array and its elements from the user. Then, we call the findLargestElement method to obtain the largest element and print it.

Python Programming Language:

def find_largest_element(arr):
    max_element = float('-inf')  # Initialize with negative infinity

    for num in arr:
        if num > max_element:
            max_element = num

    return max_element

Output:

Enter the size of the array: 6
Enter the elements of the array:
14 29 6 18 12 36
The largest element in the array is: 36

Explanation:

  • We start by initializing max_element to negative infinity, ensuring that any element in the array will be greater than this initial value.
  • Then, we loop through each element in the array. For each element, we compare it with the current max_element. If the element is greater, we update max_element with the value of the current element.
  • By the end of the loop, max_element will contain the largest value encountered in the array.

Time Complexity

This approach requires iterating through the entire array once, resulting in a time complexity of O(N), where N is the size of the array.

Space Complexity

The approach uses a constant amount of extra space, regardless of the input size, leading to a space complexity of O(1).

Approach 2 – Recursive Approach

The recursive approach involves breaking down the problem of finding the largest element in an array into smaller subproblems. In this case, we can break down the array into two parts: the first element and the rest of the array. The largest element in the entire array can then be determined by comparing the first element with the largest element in the rest of the array.

Algorithm

  • If the array has only one element, return that element as the largest.
  • Otherwise, divide the array into two parts: the first element (arr[0]) and the rest of the array (arr[1:]).
  • Recursively find the largest element in the rest of the array by calling the function with the smaller array (arr[1:]).
  • Compare the first element (arr[0]) with the result obtained from the recursive call.
  • Return the larger of the two elements as the result.

Code Implementation

Below is the implementation of the above approach in different programming languages:

C Programming Language:

#include <stdio.h>

int findLargestRecursive(int arr[], int n) {
    if (n == 1) {
        return arr[0];
    } else {
        int restMax = findLargestRecursive(arr + 1, n - 1);
        return (arr[0] > restMax) ? arr[0] : restMax;
    }
}

int main() {
    int N;
    printf("Enter the size of the array: ");
    scanf("%d", &N);

    int arr[N];
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < N; i++) {
        scanf("%d", &arr[i]);
    }

    int largest = findLargestRecursive(arr, N);
    printf("The largest element in the array is: %d\n", largest);

    return 0;
}

Output:

Enter the size of the array: 5
Enter the elements of the array:
23 8 15 42 10
The largest element in the array is: 42

Explanation:

  • Every step is similar to the steps followed in the above code.
  • The function compares the first element arr[0] with the result of the recursive call restMax. It returns the larger of the two elements using the ternary conditional operator (? :).

C++ Programming Language:

#include <iostream>
#include <climits> // For INT_MIN

int findLargestRecursive(int arr[], int n) {
    if (n == 1) {
        return arr[0];
    } else {
        int restMax = findLargestRecursive(arr + 1, n - 1);
        return (arr[0] > restMax) ? arr[0] : restMax;
    }
}

int main() {
    int N;
    std::cout << "Enter the size of the array: ";
    std::cin >> N;

    int arr[N];
    std::cout << "Enter the elements of the array:" << std::endl;
    for (int i = 0; i < N; i++) {
        std::cin >> arr[i];
    }

    int largest = findLargestRecursive(arr, N);
    std::cout << "The largest element in the array is: " << largest << std::endl;

    return 0;
}

Output:

Enter the size of the array: 5
Enter the elements of the array:
23 8 15 42 10
The largest element in the array is: 42

Explanation:

  • Every step is similar like the steps followed in the above code.

Java:

import java.util.Scanner;

public class FindLargestRecursive {
    public static int findLargestRecursive(int[] arr, int n) {
        if (n == 1) {
            return arr[0];
        } else {
            int restMax = findLargestRecursive(arr, n - 1);
            return Math.max(arr[0], restMax);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int N = scanner.nextInt();

        int[] arr = new int[N];
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < N; i++) {
            arr[i] = scanner.nextInt();
        }

        int largest = findLargestRecursive(arr, N);
        System.out.println("The largest element in the array is: " + largest);

        scanner.close();
    }
}

Output:

Enter the size of the array: 5
Enter the elements of the array:
23 8 15 42 10
The largest element in the array is: 42

Explanation:

  • Every step is similar to the steps followed in the above code.
  • The method returns the larger of the first element arr[0] and the result of the recursive call using the Math.max function.

Python:

def find_largest_recursive(arr, n):
    if n == 1:
        return arr[0]
    else:
        rest_max = find_largest_recursive(arr[1:], n - 1)
        return max(arr[0], rest_max)

# Example usage
if __name__ == "__main__":
    arr = [12, 45, 9, 33, 7]
    largest = find_largest_recursive(arr, len(arr))
    print("The largest element in the array is:", largest)

Output:

The largest element in the array is: 45

Explanation:

  • The recursive function find_largest_recursive takes an array arr and its size n as parameters and returns the largest element in the array.
  • If the array has only one element n == 1, the function directly returns that element as it is the largest in this case.
  • Otherwise, the array is divided into two parts: the first element arr[0] and the rest of the array arr[1:].
  • The function recursively calls itself with the smaller array arr[1:] and compares the first element with the result of the recursive call rest_max.
  • The function then returns the larger of the two elements arr[0] and rest_max as the largest element.

Time Complexity

The recursion breaks down the problem into smaller subproblems, but each element is visited once, resulting in a time complexity of O(N), where N is the size of the array.

Space Complexity

The recursive calls consume memory on the call stack, leading to a space complexity of O(N) due to the depth of the recursion.

Approach 3 – Using Library Function

This approach involves utilizing a built-in or library function provided by the programming language to directly find the largest element in an array. Many programming languages offer standard library functions that can efficiently solve this problem without the need for manual traversal and comparison.

Algorithm

Identify the appropriate library function provided by the programming language for finding the maximum element in an array.

Code Implementation

C:

#include <stdio.h>
#include <stdlib.h> // For qsort function

// Comparator function for qsort
int compare(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

int main() {
    int N;
    printf("Enter the size of the array: ");
    scanf("%d", &N);

    int arr[N];
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < N; i++) {
        scanf("%d", &arr[i]);
    }

    // Sort the array in ascending order
    qsort(arr, N, sizeof(int), compare);

    int largest = arr[N - 1]; // Last element after sorting is the largest
    printf("The largest element in the array is: %d\n", largest);

    return 0;
}

Output:

Enter the size of the array: 6
Enter the elements of the array separated by spaces: 18 5 32 9 27 14
The largest element in the array is: 32

Explanation:

  • The qsort() function in C is used to sort an array in ascending order. We need to provide a comparator function that defines how the elements should be compared during sorting.
  • The qsort() function is then used to sort the array in ascending order. After sorting, the largest element will be the last element of the sorted array.
  • We print the largest element as the result.

C++:

#include <iostream>
#include <algorithm> // For max_element function

int main() {
    int N;
    std::cout << "Enter the size of the array: ";
    std::cin >> N;

    int arr[N];
    std::cout << "Enter the elements of the array:" << std::endl;
    for (int i = 0; i < N; i++) {
        std::cin >> arr[i];
    }

    // Find the iterator pointing to the largest element in the array
    int *largestElementPtr = std::max_element(arr, arr + N);

    int largest = *largestElementPtr; // Dereference the iterator to get the value
    std::cout << "The largest element in the array is: " << largest << std::endl;

    return 0;
}

Output:

Enter the size of the array: 6
Enter the elements of the array separated by spaces: 18 5 32 9 27 14
The largest element in the array is: 32

Explanation:

  • The std::max_element() function is used to find the iterator pointing to the largest element in the array.
  • We dereference the iterator to get the actual largest value and print it as the result.

JAVA:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class FindLargestUsingLibrary {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int N = scanner.nextInt();

        ArrayList<Integer> arr = new ArrayList<>();
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < N; i++) {
            arr.add(scanner.nextInt());
        }

        int largest = Collections.max(arr);
        System.out.println("The largest element in the array is: " + largest);

        scanner.close();
    }
}

Output:

Enter the size of the array: 6
Enter the elements of the array separated by spaces: 18 5 32 9 27 14
The largest element in the array is: 32

Explanation:

  • The Collections.max() method in Java is used to find the maximum element in a collection (such as an ArrayList) or an array.
  • We use an ArrayList<Integer> to store the elements entered by the user.
  • The Collections.max() method is then used to find the largest element in the ArrayList.
  • We print the largest element as the result.

Python:

def main():
    N = int(input("Enter the size of the array: "))
    arr = list(map(int, input("Enter the elements of the array separated by spaces: ").split()))

    largest = max(arr)
    print("The largest element in the array is:", largest)

if __name__ == "__main__":
    main()

Output:

Enter the size of the array: 6
Enter the elements of the array separated by spaces: 18 5 32 9 27 14
The largest element in the array is: 32

Explanation:

  • The max() function in Python returns the largest element from an iterable, such as a list or an array.
  • The elements are split and converted into a list using the split() function and the map() function with int to convert them into integers.
  • We then use the max() function to find the largest element in the array and print the result.

Time Complexity

The time complexity of the library function depends on its implementation and efficiency, which can vary across programming languages. However, these library functions are often optimized for performance and can achieve O(N) time complexity.

Space Complexity

The space complexity for this approach is minimal, often O(1), as it does not involve additional memory usage proportional to the input size.

Approach 4 – Using Pointers

This approach involves utilizing pointers in languages that support them, such as C and C++, to traverse the array and identify the largest element. By maintaining a pointer that points to the largest element encountered so far, we can compare each element with the value pointed to by the pointer and update it as needed.

Algorithm:

  • Initialize a pointer maxPtr to the first element of the array.
  • Iterate through the array using a loop and a pointer currentPtr that starts from the second element.
  • If the value pointed to by currentPtr is greater than the value pointed to by maxPtr, update maxPtr to point to currentPtr.
  • After the loop, the value pointed to by maxPtr is the largest element in the array.

Code Implementation

Here’s an example using C++:

#include <iostream>

int main() {
    int N;
    std::cout << "Enter the size of the array: ";
    std::cin >> N;

    int arr[N];
    std::cout << "Enter the elements of the array:" << std::endl;
    for (int i = 0; i < N; i++) {
        std::cin >> arr[i];
    }

    int *maxPtr = &arr[0]; // Initialize pointer to the first element

    for (int i = 1; i < N; i++) {
        if (arr[i] > *maxPtr) {
            maxPtr = &arr[i]; // Update pointer if a larger value is found
        }
    }

    std::cout << "The largest element in the array is: " << *maxPtr << std::endl;

    return 0;
}

Output:

Enter the size of the array: 6
Enter the elements of the array:
21 10 30 8 15 5
The largest element in the array is: 30

Explanation:

  • We iterate through the array using a loop, starting from the second element. For each element, we compare it with the value pointed to by maxPtr. If the element is greater, we update maxPtr to the current element.
  • At the end, the value pointed to by maxPtr is the largest element in the array.

Time Complexity

The time complexity of this approach is O(N), where N is the size of the array.

Space complexity

The space complexity of this approach is O(1), which is constant.

Conclusion

  • Several approaches are available to solve this problem efficiently:
  • The iterative approach involves iterating through the array and updating the maximum element.
  • The recursive approach breaks down the problem by comparing the first element with the largest element in the rest of the array.
  • Using library functions provides a convenient and optimised way to find the maximum element.
  • Utilizing pointers allows tracking the largest element while traversing the array.
  • Each approach has its own time and space complexities, catering to different programming needs.
  • The choice of approach depends on factors such as language capabilities, coding style, and optimisation requirements.

Author