Skip to content
Related Articles

Related Articles

Python Program to find largest element in an array

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 21 Jul, 2022

Given an array, find the largest element in it.

Input : arr[] = {10, 20, 4}
Output : 20

Input : arr[] = {20, 10, 20, 4, 100}
Output : 100

Approach 1:

Python3




# Python3 program to find maximum
# in arr[] of size n
 
# python function to find maximum
# in arr[] of size n
 
 
def 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 Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr, n)
print("Largest in given array ", Ans)
 
# This code is contributed by Smitha Dinesh Semwal


Output

Largest in given array  9808

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 2 (Using built-in function max()):

Here we will use the inbuilt method max() to find the maximum of the array. Below is the implementation of the approach.

Python3




# Python3 program to find maximum
# in arr[] of size n
def largest(arr, n):
    ans = max(arr)
    return ans;
 
# Driver code
if __name__ == '__main__':
    arr = [10, 324, 45, 90, 9808]
    n = len(arr)
    print ("Largest in given array ", largest(arr, n))


Output

Largest in given array  9808

Approach 3 (Using sort() function):

Here we use the sort() function to sort the array. The largest element will be the last element of the sorted array. Below is the implementation of the approach.

Python3




# Python3 program to find maximum
# in arr[] of size n
 
def largest(arr, n):
 
    # Sort the array
    arr.sort()
 
    # The last element of the
    # array is the largest element
    return arr[n-1]
    # or return arr[-1]
 
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr, n)
print("Largest in given array ", Ans)
 
# This code is contributed by Induri Deepthi


Output

Largest in given array  9808

Please refer complete article on Program to find largest element in an array for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!