Find the maximum of Array 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++
// C++ program to find maximum in arr[] of size n #include <bits/stdc++.h> using namespace std; // Returns maximum in arr[] of size n int largest( int arr[], int n) { return *max_element(arr, arr + n); } // Driver code int main() { int arr[] = { 10, 324, 45, 90, 9808 }; int n = sizeof (arr) / sizeof (arr[0]); // Function call cout << largest(arr, n); return 0; } |
Java
// Java program to find maximum in arr[] of size n import 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; // Function call System.out.println(largest(arr, n)); } } // This code is contributed by anuj_67. |
Python3
# Python 3 program to find maximum in arr[] of size n # Returns maximum in arr[] of size n def largest(arr, n): return max (arr) # Driver code if __name__ = = '__main__' : arr = [ 10 , 324 , 45 , 90 , 9808 ] n = len (arr) # Function call print (largest(arr, n)) # This code is contributed by # Smitha Dinesh Semwal |
C#
// C# program to find maximum in arr[] of size n using 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 |
Javascript
<script> // Javascript program to find maximum in arr[] of size n // Returns maximum in arr[] of size n function 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> |
PHP
<?php // PHP program to find maximum in arr[] of size n // Returns maximum in arr[] of size n function 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. ?> |
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.
Refer below article for more methods: Program to find the minimum (or maximum) element of an array
Program to find largest element in an Array
Given an array arr[] of size N, the task is to find the largest element in the given array.
Examples:
Input: arr[] = {10, 20, 4}
Output: 20
Explanation: Among 10, 20 and 4, 20 is the largest.Input : arr[] = {20, 10, 20, 4, 100}
Output : 100