Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find Second largest element in an array | Set 2
Next article icon

Largest element in an Array

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr. 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

Table of Content

  • Iterative Approach – O(n) Time and O(1) Space
  • Recursive Approach – O(n) Time and O(n) Space
  • Using Library Methods – O(n) Time and O(1) Space

Iterative Approach – O(n) Time and O(1) Space

The approach to solve this problem is to traverse the whole array and find the maximum among them.

C++
#include <iostream> #include <vector> using namespace std;  int largest(vector<int>& arr) {     int max = arr[0];      //Traverse  from second and compare     // every element with current max     for (int i = 1; i < arr.size(); i++)         if (arr[i] > max)             max = arr[i];      return max; }  int main() {     vector<int> arr = {10, 324, 45, 90, 9808};     cout << largest(arr);     return 0; } 
C
#include <stdio.h>  int largest(int arr[], int n) {     int i;     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("%d", largest(arr, n));     return 0; } 
Java
import java.io.*;  class GfG {     static int largest(int[] arr) {         int max = arr[0];          // Traverse array elements from second and         // compare every element with current max         for (int i = 1; i < arr.length; i++)             if (arr[i] > max)                 max = arr[i];          return max;     }      public static void main(String[] args) {         int arr[] = { 10, 324, 45, 90, 9808 };         System.out.println(largest(arr));     } } 
Python
def largest(arr, n):     mx = arr[0]      # Traverse array elements from second     # and compare every element with     # current max     for i in range(1, n):         if arr[i] > mx:             mx = arr[i]      return mx  if __name__ == '__main__':     arr = [10, 324, 45, 90, 9808]     n = len(arr)          ans = largest(arr, n)          print(ans) 
C#
using System; using System.Collections.Generic;  class GfG {     static int Largest(List<int> arr) {         int max = arr[0];          // Traverse from second and compare         // every element with current max         for (int i = 1; i < arr.Count; i++)             if (arr[i] > max)                 max = arr[i];          return max;     }      static void Main() {         List<int> arr = new List<int> { 10, 324, 45, 90, 9808 };         Console.WriteLine(Largest(arr));     } } 
JavaScript
function largest(arr) {     let max = arr[0];      // Traverse from second and compare     // every element with current max     for (let i = 1; i < arr.length; i++)         if (arr[i] > max)             max = arr[i];      return max; }  // Driver Code const arr = [10, 324, 45, 90, 9808]; console.log(largest(arr)); 

Output
9808

Recursive Approach – O(n) Time and O(n) Space

The idea is similar to the iterative approach. Here the traversal of the array is done recursively instead of an iterative loop. 

C++
#include <iostream> #include <vector> using namespace std;  int findMax(vector<int>& arr, int i) {       // Last index returns the element     if (i == arr.size() - 1) {         return arr[i];     }      // Find the maximum from the rest of the vector     int recMax = findMax(arr, i + 1);      // Compare with i-th element and return     return max(recMax, arr[i]); }  int largest(vector<int>& arr) {   return findMax(arr,0); }  int main() {     vector<int> arr = {10, 324, 45, 90, 9808};     cout << largest(arr);     return 0; } 
C
#include <stdio.h>  int findMax(int arr[], int size, int i) {        // Last index returns the element     if (i == size - 1) {         return arr[i];     }      // Find the maximum from the rest of the array     int recMax = findMax(arr, size, i + 1);      // Compare with i-th element and return     return (recMax > arr[i]) ? recMax : arr[i]; }  int largest(int arr[], int size) {     return findMax(arr, size, 0); }  int main() {     int arr[] = {10, 324, 45, 90, 9808};     int size = sizeof(arr) / sizeof(arr[0]);     printf("%d", largest(arr, size));     return 0; } 
Java
import java.util.Arrays;  class GfG {     static int findMax(int[] arr, int i) {                // Last index returns the element         if (i == arr.length - 1) {             return arr[i];         }          // Find the maximum from the rest of the array         int recMax = findMax(arr, i + 1);          // Compare with i-th element and return         return Math.max(recMax, arr[i]);     }      static int largest(int[] arr) {         return findMax(arr, 0);     }      public static void main(String[] args) {         int[] arr = {10, 324, 45, 90, 9808};         System.out.println(largest(arr));     } } 
Python
def findMax(arr, i):        # Last index returns the element     if i == len(arr) - 1:         return arr[i]      # Find the maximum from the rest of the list     recMax = findMax(arr, i + 1)      # Compare with i-th element and return     return max(recMax, arr[i])   def largest(arr):     return findMax(arr, 0)  if __name__ == '__main__':   arr = [10, 324, 45, 90, 9808]   print(largest(arr)) 
C#
using System;  class GfG {     static int FindMax(int[] arr, int i) {                // Last index returns the element         if (i == arr.Length - 1) {             return arr[i];         }          // Find the maximum from the rest of the array         int recMax = FindMax(arr, i + 1);          // Compare with i-th element and return         return Math.Max(recMax, arr[i]);     }      static int Largest(int[] arr) {         return FindMax(arr, 0);     }      static void Main() {         int[] arr = {10, 324, 45, 90, 9808};         Console.WriteLine(Largest(arr));     } } 
JavaScript
function findMax(arr, i) {     // Last index returns the element     if (i === arr.length - 1) {         return arr[i];     }      // Find the maximum from the rest of the array     let recMax = findMax(arr, i + 1);      // Compare with i-th element and return     return Math.max(recMax, arr[i]); }  function largest(arr) {     return findMax(arr, 0); }  // Driver Code const arr = [10, 324, 45, 90, 9808]; console.log(largest(arr)); 

Output
9808

Using Library Methods – O(n) Time and O(1) Space

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.  

C++
#include <iostream> #include <vector> #include <algorithm> using namespace std;  int largest(vector<int>& arr) {     return *max_element(arr.begin(), arr.end()); }  int main() {     vector<int> arr = {10, 324, 45, 90, 9808};     cout << largest(arr);     return 0; } 
C
#include <stdio.h> #include <stdlib.h>  int compare(const void* a, const void* b) {     return (*(int*)a - *(int*)b); }  int largest(int arr[], int n) {     qsort(arr, n, sizeof(int), compare);     return arr[n - 1]; }  int main() {     int arr[] = {10, 324, 45, 90, 9808};     int n = sizeof(arr) / sizeof(arr[0]);     printf("%d\n", largest(arr, n));     return 0; } 
Java
import java.io.*; import java.util.*;  class GfG {      static int largest(int[] arr) {         Arrays.sort(arr);         return arr[arr.length - 1];     }      static public void main(String[] args) {         int[] arr = { 10, 324, 45, 90, 9808 };         System.out.println(largest(arr));     } } 
Python
# Python program to find maximum in arr[] of size n  def largest(arr):     return max(arr)  if __name__ == '__main__':   arr = [10, 324, 45, 90, 9808]   print(largest(arr)) 
C#
using System; using System.Linq; using System.Collections.Generic;  class GfG {   static int largest(List<int> arr) {           return arr.Max();       }        static public void Main() {  		List<int> arr = new List<int> { 10, 324, 45, 90, 9808 };         Console.WriteLine(largest(arr));     } } 
JavaScript
// Function to find the largest number in an array function largest(arr) {     return Math.max(...arr); }  // Driver Code const arr = [10, 324, 45, 90, 9808]; console.log(largest(arr)); 

Output
9808


Next Article
Find Second largest element in an array | Set 2
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • Matrix
  • Searching
  • Basic Coding Problems
  • Order-Statistics
Practice Tags :
  • Arrays
  • Matrix
  • Searching

Similar Reads

  • Kth Largest Element in an Array
    Given an integer array arr[] of size n elements and a positive integer K, the task is to return the kth largest element in the given array (not the Kth distinct element). Examples: Input: [1, 23, 12, 9, 30, 2, 50], K = 3Output: 23 Input: [12, 3, 5, 7, 19], K = 2Output: 12 Table of Content [Naive App
    15+ min read
  • Second Largest Element in an Array
    Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array. Note: If the second largest element does not exist, return -1. Examples: Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the s
    14 min read
  • Find k largest elements in an array
    Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order. Examples: Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23] Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17] Table of Content
    15+ min read
  • Find Second largest element in an array | Set 2
    Given an array arr[] consisting of N integers, the task is to find the second largest element in the given array using N+log2(N) - 2 comparisons. Examples: Input : arr[] = {22, 33, 14, 55, 100, 12}Output : 55 Input : arr[] = {35, 23, 12, 35, 19, 100}Output : 35 Sorting and Two-Traversal Approach: Re
    9 min read
  • Most frequent element in an array
    Given an array, the task is to find the most frequent element in it. If there are multiple elements that appear a maximum number of times, return the maximum element. Examples: Input : arr[] = [1, 3, 2, 1, 4, 1]Output : 1Explanation: 1 appears three times in array which is maximum frequency. Input :
    10 min read
  • Largest element after K operations on Array
    Given array A[] (1 <= A[i] <= 108) of size N (2 <= N <= 103) and integer K (1 <= K <= 108), the task is to find the largest element of the array after performing the given operation at most K times, in one operation choose i from 1 to N - 1 such that A[i] <= A[i + 1] and then in
    13 min read
  • Maximum element in a sorted and rotated array
    Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array. Input: arr[] = {3, 2, 2, 2}Output: 3Expl
    7 min read
  • Largest pair sum in an array
    Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
    10 min read
  • Third largest element in an array of distinct elements
    Given an array of n integers, the task is to find the third largest element. All the elements in the array are distinct integers. Examples : Input: arr[] = {1, 14, 2, 16, 10, 20}Output: 14Explanation: Largest element is 20, second largest element is 16 and third largest element is 14Input: arr[] = {
    12 min read
  • Type of array and its maximum element
    Given an array, it can be of 4 types. Ascending Descending Ascending Rotated Descending Rotated Find out which kind of array it is and return the maximum of that array. Examples: Input : arr[] = { 2, 1, 5, 4, 3} Output : Descending rotated with maximum element 5 Input : arr[] = { 3, 4, 5, 1, 2} Outp
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences