Program to find largest element in an array - GeeksforGeeks

30 Mar, 2022
Given an array arr of size N, the task is to find the largest element in the given array. 
Example: 
Input: arr[] = {10, 20, 4}Output: 20
Input : arr[] = {20, 10, 20, 4, 100}Output : 100
Approach 1 – Linear Traversal: One of the most simplest and basic approach to solve this problem is to simply traverse the whole list and find the maximum among them. 
Follow the steps below to implement this idea:
Create a local variable max to store the maximum among the list
Initialize max with the first element initially, to start the comparison.
Then traverse the given array from second element till end, and for each element:Compare the current element with maxIf the current element is greater than max, then replace the value of max with the current element.
Compare the current element with max
If the current element is greater than max, then replace the value of max with the current element.
At the end, return and print the value of the largest element of array stored in max.
Below is the implementation of the above approach: 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum// in arr[] of size n#include <bits/stdc++.h>using namespace std; int largest(int arr[], int n){    int i;         // Initialize maximum element    int max = arr[0];     // Traverse array elements    // from second and compare    // every element with current max    for (i = 1; i < n; i++)        if (arr[i] > max)            max = arr[i];     return max;} // Driver Codeint main(){    int arr[] = {10, 324, 45, 90, 9808};    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Largest in given array is "         << largest(arr, n);    return 0;} // This Code is contributed// by Shivi_Aggarwal
// C program to find maximum in arr[] of size n#include <stdio.h> // C function to find maximum in arr[] of size nint largest(int arr[], int n){    int i;        // Initialize maximum element    int max = arr[0];     // Traverse array elements from second and    // compare every element with current max     for (i = 1; i < n; i++)        if (arr[i] > max)            max = arr[i];     return max;} int main(){    int arr[] = {10, 324, 45, 90, 9808};    int n = sizeof(arr)/sizeof(arr[0]);    printf("Largest in given array is %d", largest(arr, n));    return 0;}
// Java Program to find maximum in arr[]class Test{     static int arr[] = {10, 324, 45, 90, 9808};           // Method to find maximum in arr[]     static int largest()     {         int i;                   // Initialize maximum element         int max = arr[0];                // Traverse array elements from second and         // compare every element with current max          for (i = 1; i < arr.length; i++)             if (arr[i] > max)                 max = arr[i];                return max;     }           // Driver method     public static void main(String[] args)     {         System.out.println("Largest in given array is " + largest());        } }
# Python3 program to find maximum# in arr[] of size n # Function to find maximum# in arr[] of size ndef largest(arr,n):   # Initialize maximum element   max = arr[0]              # Traverse array elements from second            # and compare every element with             # current max            for i in range(1, n):              if arr[i] > max:                  max = arr[i]            return max # Driver Codearr = [10, 324, 45, 90, 9808]n = len(arr) #calculating length of an arrayAns = largest(arr,n) # display maxprint ("Largest in given array is",Ans) # This code is contributed by Jai Parkash Bhardwaj# and improved by ssaha3475
// C# Program to find maximum in arr[]using System; class GFG {         static int []arr = {10, 324, 45, 90, 9808};         // Method to find maximum in arr[]    static int largest()    {        int i;                 // Initialize maximum element        int max = arr[0];             // Traverse array elements from second and        // compare every element with current max        for (i = 1; i < arr.Length; i++)            if (arr[i] > max)                max = arr[i];             return max;    }         // Driver method    public static void Main()    {        Console.WriteLine("Largest in given "                  + "array is " + largest());    }} // This code is contributed by anuj_67.
<?php// PHP program to find maximum// in arr[] of size n // PHP function to find maximum// in arr[] of size nfunction largest($arr, $n){    $i;         // Initialize maximum element    $max = $arr[0];     // Traverse array elements    // from second and    // compare every element    // with current max    for ($i = 1; $i < $n; $i++)        if ($arr[$i] > $max)            $max = $arr[$i];     return $max;}           // Driver Code    $arr= array(10, 324, 45, 90, 9808);    $n = sizeof($arr);    echo "Largest in given array is "                 , largest($arr, $n);     // This code is contributed by aj_36?>
<script> // JavaScript program to find// maximum in arr[] of size n       function largest(arr) {        let i;               // Initialize maximum element        let max = arr[0];           // Traverse array elements         // from second and compare        // every element with current max         for (i = 1; i < arr.length; i++) {            if (arr[i] > max)                max = arr[i];        }               return max;}         // Driver code    let arr = [10, 324, 45, 90, 9808];    document.write("Largest in given array is " + largest(arr));      // This code is contributed by Surbhi Tyagi   </script>
Largest in given array is 9808
Time complexity: O(N), to traverse the Array completely.Auxiliary Space: O(1), as only an extra variable is created, which will take O(1) space.
Approach 2: Using Library Function: Most of the languages have a relevant max() type in-built function to find the maximum element, such as  std::max_element in C++. We can use this function to directly find the maximum element.  
Below is the implementation of the above approach: 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum in arr[] of size n#include <bits/stdc++.h>using namespace std; // returns maximum in arr[] of size nint largest(int arr[], int n){    return *max_element(arr, arr+n);} int main(){    int arr[] = {10, 324, 45, 90, 9808};    int n = sizeof(arr)/sizeof(arr[0]);    cout << largest(arr, n);    return 0;}
// Java program to// find maximum in// arr[] of size nimport java .io.*;import java.util.*; class GFG{         // returns maximum in    // arr[] of size n    static int largest(int []arr,                         int n)    {        Arrays.sort(arr);        return arr[n - 1];    }     // Driver code    static public void main (String[] args)    {        int []arr = {10, 324, 45,                     90, 9808};        int n = arr.length;        System.out.println(largest(arr, n));    }} // This code is contributed// by anuj_67.
# Python 3 program to find# maximum in arr[] of size n # returns maximum# in arr[] of size ndef largest(arr, n):     return max(arr) # driver codearr = [10, 324, 45, 90, 9808]n = len(arr) print(largest(arr, n)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to find maximum in// arr[] of size nusing System;using System.Linq; public class GFG {         // returns maximum in arr[]    static int Largest(int[] arr)    {        return arr.Max();    }     // Driver code    static public void Main ()    {        int[] arr = {10, 324, 45, 90, 9808};        Console.WriteLine(Largest(arr));    }} // This code is contributed by anuj_67.// Minor code cleanup by shanmukha7
<?php// PHP program to find maximum// in arr[] of size n // returns maximum in// arr[] of size nfunction largest( $arr, $n){    return max($arr);}     // Driver COde    $arr = array(10, 324, 45, 90, 9808);    $n = count($arr);    echo largest($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find maximum in arr[] of size n // returns maximum in arr[] of size nfunction largest(arr, n){    arr.sort();    return arr[n-1];}     let arr = [10, 324, 45, 90, 9808];    let n = arr.length;    document.write(largest(arr, n));   //This code is contributed by Mayank Tyagi </script>
9808
Time complexity: O(N), since the in-built max_element() function takes O(N) time.Auxiliary Space: O(1), as only an extra variable is created, which will take O(1) space. 
YouTubeGeeksforGeeks507K subscribersFind largest element in an array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=En68ipRaFOU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Refer below article for more methods: Program to find the minimum (or maximum) element of an array
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
vt_m
Shivi_Aggarwal
ShayekhBinIslam
jaibhardwaj1997
surbhityagi15
mayanktyagi1709
shanmukha7
RishabhPrabhu
Order-Statistics
Arrays
Matrix
School Programming
Searching
Arrays
Searching
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Print a given matrix in spiral form
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)