The Wayback Machine - https://web.archive.org/web/20240818163938/https://www.geeksforgeeks.org/find-the-largest-three-elements-in-an-array/
Open In App

Find the largest three distinct elements in an array

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array with all distinct elements, find the largest three elements.

Examples :

Input: arr[] = {10, 4, 3, 50, 23, 90}
Output: 90, 50, 23

Input: arr[] = { 6, 8, 9, 2, 1, 10}
Output: 10, 8, 9

Approach:

Initialize three variables, `first`, `second`, and `third`, to store the three largest elements. We then iterate through the array and compare each element with the current values of `first`, `second`, and `third`. If an element is greater than `first`, we update `third` to `second`, `second` to `first`, and `first` to the new element. If an element is greater than `second` but not `first`, we update `third` to `second` and `second` to the new element. If an element is greater than `third` but not `second` or `first`, we update `third` to the new element. After iterating through the entire array, `first`, `second`, and `third` will contain the three largest elements, which we can then print as the result.

  • Set first, second, and third to the minimum possible integer value (INT_MIN).
  • Iterate through the Array
    • For each element arr[i]:
      • If arr[i] is greater than first:
        • Update third to second, second to first, and first to arr[i].
      • Otherwise, if arr[i] is greater than second and not equal to first:
        • Update third to second and second to arr[i].
      • Otherwise, if arr[i] is greater than third and not equal to second and first:
        • Update third to arr[i].
  • Print the values of first, second, and third as the three largest elements.

Below is the implementation of the above algorithm.

C++
// C++ program for find the largest 
// three elements in an array
#include <bits/stdc++.h> 
using namespace std;

// Function to print three largest elements 
void print3largest(int arr[], int arr_size) 
{ 
    int first, second, third; 

    // There should be atleast three elements 
    if (arr_size < 3) 
    { 
        cout << " Invalid Input "; 
        return; 
    } 

    third = first = second = INT_MIN; 
    for(int i = 0; i < arr_size; i++) 
    { 
        
        // If current element is
        // greater than first
        if (arr[i] > first)
        { 
            third = second; 
            second = first; 
            first = arr[i]; 
        } 

        // If arr[i] is in between first
        // and second then update second 
        else if (arr[i] > second && arr[i] != first)
        { 
            third = second; 
            second = arr[i]; 
        } 

        else if (arr[i] > third && arr[i] != second && arr[i] != first) 
            third = arr[i]; 
    } 

    cout << "Three largest elements are "
        << first << " " << second << " "
        << third << endl; 
} 

// Driver code
int main() 
{ 
    int arr[] = { 12, 13, 1, 10, 34, 11, 34 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    
    print3largest(arr, n); 
    return 0; 
} 

// This code is contributed by Anjali_Chauhan
C
// C program for find the largest 
// three elements in an array
#include <limits.h> /* For INT_MIN */
#include <stdio.h>

/* Function to print three largest elements */
void print3largest(int arr[], int arr_size)
{
    int i, first, second, third;

    /* There should be atleast three elements */
    if (arr_size < 3) {
        printf(" Invalid Input ");
        return;
    }

    third = first = second = INT_MIN;
    for (i = 0; i < arr_size; i++) {
        /* If current element is greater than first*/
        if (arr[i] > first) {
            third = second;
            second = first;
            first = arr[i];
        }

        /* If arr[i] is in between first and second then update second  */
        else if (arr[i] > second) {
            third = second;
            second = arr[i];
        }

        else if (arr[i] > third)
            third = arr[i];
    }

    printf("Three largest elements are %d %d %d\n", first, second, third);
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 13, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print3largest(arr, n);
    return 0;
}
/*This code is edited by Ayush Singla(@ayusin51)*/
Java
// Java code to find largest three elements
// in an array

class PrintLargest {
    /* Function to print three largest elements */
    static void print3largest(int arr[], int arr_size)
    {
        int i, first, second, third;

        /* There should be atleast three elements */
        if (arr_size < 3) {
            System.out.print(" Invalid Input ");
            return;
        }

        third = first = second = Integer.MIN_VALUE;
        for (i = 0; i < arr_size; i++) {
            /* If current element is greater than
            first*/
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }

            /* If arr[i] is in between first and
            second then update second  */
            else if (arr[i] > second) {
                third = second;
                second = arr[i];
            }

            else if (arr[i] > third)
                third = arr[i];
        }

        System.out.println("Three largest elements are " + first + " " + second + " " + third);
    }

    /* Driver program to test above function*/
    public static void main(String[] args)
    {
        int arr[] = { 12, 13, 1, 10, 34, 1 };
        int n = arr.length;
        print3largest(arr, n);
    }
}
/*This code is contributed by Prakriti Gupta 
and edited by Ayush Singla(@ayusin51)*/
Python
def print3largest(arr):
    arr_size = len(arr)
    
    # There should be atleast three elements
    if arr_size < 3:
        print("Invalid Input")
        return
    
    third = first = second = float('-inf')
    
    for i in range(arr_size):
        # If current element is greater than first
        if arr[i] > first:
            third = second
            second = first
            first = arr[i]
        
        # If arr[i] is in between first and second then update second
        elif arr[i] > second and arr[i] != first:
            third = second
            second = arr[i]
        
        elif arr[i] > third and arr[i] != second and arr[i] != first:
            third = arr[i]

    print("Three largest elements are", first, second, third)

# Driver code
arr = [12, 13, 1, 10, 34, 11, 34]
print3largest(arr)
C#
// C# code to find largest
// three elements in an array
using System;

class PrintLargest {

    // Function to print three
    // largest elements
    static void print3largest(int[] arr,
                              int arr_size)
    {
        int i, first, second, third;

        // There should be atleast three elements
        if (arr_size < 3) {
            Console.WriteLine("Invalid Input");
            return;
        }

        third = first = second = 000;
        for (i = 0; i < arr_size; i++) {
            // If current element is
            // greater than first
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }

            // If arr[i] is in between first
            // and second then update second
            else if (arr[i] > second && arr[i] != first) {
                third = second;
                second = arr[i];
            }

            else if (arr[i] > third && arr[i]!=second)
                third = arr[i];
        }

        Console.WriteLine("Three largest elements are " + first + " " + second + " " + third);
    }

    // Driver code
    public static void Main()
    {
        int[] arr = new int[] { 12, 13, 1, 10, 34, 1 };
        int n = arr.Length;
        print3largest(arr, n);
    }
}

// This code is contributed by KRV and edited by Ayush Singla(@ayusin51).
JavaScript
<script>

// Javascript program for find the largest 
// three elements in an array

// Function to print three largest elements 
function print3largest(arr, arr_size) 
{ 
    let first, second, third; 

    // There should be atleast three elements 
    if (arr_size < 3) 
    { 
        document.write(" Invalid Input "); 
        return; 
    } 

    third = first = second = Number.MIN_VALUE; 
    for(let i = 0; i < arr_size; i++) 
    { 
        
        // If current element is
        // greater than first
        if (arr[i] > first)
        { 
            third = second; 
            second = first; 
            first = arr[i]; 
        } 

        // If arr[i] is in between first
        // and second then update second 
        else if (arr[i] > second)
        { 
            third = second; 
            second = arr[i]; 
        } 

        else if (arr[i] > third) 
            third = arr[i]; 
    } 

    document.write("Three largest elements are "
        + first + " " + second + " "
        + third + "<br>"); 
} 

// Driver code
    let arr = [ 12, 13, 1, 10, 34, 1 ]; 
    let n = arr.length; 
    
    print3largest(arr, n); 
    
// This is code is contributed by Mayank Tyagi

</script>
PHP
<?php
// PHP code to find largest 
// three elements in an array

// Function to print 
// three largest elements
function print3largest($arr, $arr_size)
{
    $i; $first; $second; $third;

    // There should be atleast
    // three elements 
    if ($arr_size < 3)
    {
        echo " Invalid Input ";
        return;
    }

    $third = $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i ++)
    {
        // If current element is
        // greater than first
        if ($arr[$i] > $first)
        {
            $third = $second;
            $second = $first;
            $first = $arr[$i];
        }

        // If arr[i] is in between first 
        // and second then update second 
        else if ($arr[$i] > $second)
        {
            $third = $second;
            $second = $arr[$i];
        }

        else if ($arr[$i] > $third)
            $third = $arr[$i];
    }

    echo "Three largest elements are ", 
       $first, " ", $second, " ", $third;
}


// Driver Code
$arr = array(12, 13, 1, 
             10, 34, 1);
$n = count($arr);
print3largest($arr, $n);

// This code is contributed by anuj_67 and edited by Ayush Singla(@ayusin51).
?>

Output
Three largest elements are 34 13 12

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




Previous Article
Next Article

Similar Reads

Find three closest elements from given three sorted arrays
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15 10Explanation: 10 from A, 15 from B and 10 from C
15+ min read
Find the lexicographically largest array containing all distinct elements from each prefix of the given array
Given an array arr[] of length N. The task is to find a lexicographically largest array res[] of the same length such that each prefix of res[] includes all distinct elements present in the corresponding prefix of array arr[]. Examples: Input: N = 6, arr[] = {2, 5, 3, 2, 6, 5}Output: res[] = {2, 5, 3, 6, 6, 6}Explanation: This can be verified that
7 min read
Find three element from given three arrays such that their sum is X | Set 2
Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A[0] + B[1] + C[0] = 2 + 6 + 4 = 12Input: A[] = {2}
9 min read
Find three element from different three arrays such that a + b + c = sum
Given three integer arrays and a "sum", the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays. Examples : Input : a1[] = { 1 , 2 , 3 , 4 , 5 }; a2[] = { 2 , 3 , 6 , 1 , 2 }; a3[] = { 3 , 2 , 4 , 5 , 6 }; sum = 9 Output : Yes 1 + 2 + 6 = 9 here 1 from a1[] and 2 from a2[] a
15+ min read
Find all distinct three digit numbers from given array of digits
Given an array containing digits[], where each element is a single digit integer. The array may contain duplicates. The task is to find all the unique integers that follow the given requirements: The integer consists of the concatenation of three elements from digits in any arbitrary order.The integer does not have leading zeros. Examples: Input: d
6 min read
Javascript Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output
6 min read
Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output
15+ min read
Number of quadruples where the first three terms are in AP and last three terms are in GP
Given an array arr[] of N integers. The task is to find the number of index quadruples (i, j, k, l) such that a[i], a[j] and a[k] are in AP and a[j], a[k] and a[l] are in GP. All the quadruples have to be distinct.Examples: Input: arr[] = {2, 6, 4, 9, 2} Output: 2 Indexes of elements in the quadruples are (0, 2, 1, 3) and (4, 2, 1, 3) and correspon
9 min read
Find distinct characters in distinct substrings of a string
Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.Examples: Input: str = "ABCA" Output: 18 Distinct sub-stringsDistinct charactersA1AB2ABC3ABCA3B1BC2BCA3C1CA2 Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: str = "AAAB" Output: 10 Approach: Take all possible sub-strings
5 min read
Represent (2 / N) as the sum of three distinct positive integers of the form (1 / m)
Given a positive integer N, the task is to represent the fraction 2 / N as the sum of three distinct positive integers of the form 1 / m i.e. (2 / N) = (1 / x) + (1 / y) + (1 / z) and print x, y and z.Examples: Input: N = 3 Output: 3 4 12 (1 / 3) + (1 / 4) + (1 / 12) = ((4 + 3 + 1) / 12) = (8 / 12) = (2 / 3) i.e. 2 / NInput: N = 28 Output: 28 29 81
4 min read
Count distinct Strings made by removing three consecutive characters
Given a string S of length N(N &gt; 3), the task is to count distinct strings that can be made by removing three consecutive characters from the original string. Examples: Input: S = "aaabcc"Output: 4 Explanation: "bcc", "acc", "aac", "aaa" Input: S = "aaaaa"Output: 1 Explanation: "aaa" Approach: This can be solved with the following idea: We have
4 min read
Check whether a number has exactly three distinct factors or not
Given a positive integer n(1 &lt;= n &lt;= 1018). Check whether a number has exactly three distinct factors or not. Print "Yes" if it has otherwise "No". Examples : Input : 9Output: YesExplanationNumber 9 has exactly three factors:1, 3, 9, hence answer is 'Yes'Input : 10Output : NoRecommended PracticeThree distinct factorsTry It!Simple approach is
10 min read
Count of subarrays with largest element at least twice the largest of remaining elements
Given an array arr[] consisting of N positive integers, the task is to find the count of subarrays such that the maximum element of the subarray is greater than twice the maximum of all other elements of the array. Examples: Input: arr[] = {1, 6, 10, 9, 7, 3}Output: 4Explanation:Below are the subarrays satisfying the given condition: Consider the s
14 min read
Largest N digit number divisible by given three numbers
Given four integers x, y, z, and n, the task is to find the largest n digit number which is divisible by x, y, and z. Examples: Input: x = 2, y = 3, z = 5, n = 4 Output: 9990 9990 is the largest 4-digit number which is divisible by 2, 3 and 5.Input: x = 3, y = 23, z = 6, n = 2 Output: Not possible Approach: Find the largest n digit number i.e. pow(
9 min read
Largest product that can be obtained by multiplying any three integers from list
Geek is playing a video game that contains N monsters having varying power denoted by power[i]. Geek will play total Q rounds and for each round, the power of Geek is Q[i]. He can kill all monsters having power &#x2264 Q[i]. All the monsters which were dead in the previous round will be reborn, such that for each round there will be N monsters. Sin
11 min read
Count of elements which are second smallest among three consecutive elements
Given a permutation P of first N natural numbers. The task is to find the number of elements Pi such that Pi is second smallest among Pi - 1, Pi and Pi + 1.Examples: Input: P[] = {2, 5, 1, 3, 4} Output: 1 3 is the only such element.Input: P[] = {1, 2, 3, 4} Output: 2 Approach: Traverse the permutation from 1 to N - 2 ( zero-based indexing) and chec
5 min read
Create Array of distinct elements where odd indexed elements are multiple of left neighbour
Given an integer N, the task is to generate an array A[] of length N such that it satisfies the following conditions for all 1 ? i ? N?1: Ai is multiple of Ai-1 when i is oddAi is not multiple of Ai-1 when i is evenAll Ai are pairwise distinct1 ? Ai ? 2?N Note: If there are multiple answers print any of them. Examples: Input: N = 4Output: 3 6 4 8 ?
5 min read
Length of array pair formed where one contains all distinct elements and other all same elements
Given an array arr[], the task is to determine the maximum possible size of two arrays of the same size that can be created using the given array elements, such that in one array all the elements are distinct and in the other, all elements are the same. Note: It is not mandatory to use all the elements of the given array to build the two arrays. Ex
6 min read
Split an array containing N elements into K sets of distinct elements
Given two integers N and K and an array arr[] consisting of duplicate elements, the task is to split N elements into K sets of distinct elements.Examples: Input: N = 5, K = 2, arr[] = {3, 2, 1, 2, 3} Output: ( 3 2 1 ) ( 2 3 )Input: N = 5, K = 2, arr[] = {2, 1, 1, 2, 1} Output: -1 Explanation: It is not possible to split all the elements into K sets
7 min read
Longest remaining array of distinct elements possible after repeated removal of maximum and minimum elements of triplets
Given an array arr[] consisting of N integers, the task is to repeatedly select triplets and remove the maximum and minimum elements from the triplets in each operation, such that the remaining array is of longest possible length and consists only of distinct elements. Examples: Input: N = 5, arr[] = {1, 2, 1, 3, 7}&lt; Output: 3 Explanation: Selec
6 min read
Maximize distinct elements of Array by combining two elements or splitting an element
Given an array arr[] of length N, the task is to maximize the number of distinct elements in the array by performing either of the following operations, any number of times: For an index i(0 ≤ i &lt; N), replace arr[i] with a and b such that arr[i] = a + b.For two indices i (0 ≤ i &lt; N) and n (0 ≤ n &lt; N), Replace arr[n] with (arr[i] + arr[n]).
9 min read
Find common elements in three linked lists
Given three linked lists, find all common elements among the three linked lists. Examples: Input : 10 15 20 25 12 10 12 13 15 10 12 15 24 25 26 Output : 10 12 15 Input : 1 2 3 4 5 1 2 3 4 6 9 8 1 2 4 5 10 Output : 1 2 4 Method 1 : (Simple) Use three-pointers to iterate the given three linked lists and if any element common print that element. Time
11 min read
Program to find the smallest element among three elements
Given three numbers. The task is to find the smallest among the given three numbers. Examples: Input: first = 15, second = 16, third = 10 Output: 10 Input: first = 5, second = 3, third = 6 Output: 3 Approach: Check if the first element is smaller than or equal to second and third. If yes then print it.Else if check if the second element is smaller
5 min read
Find minimum sum such that one of every three consecutive elements is taken
Given an array of n non-negative numbers, the task is to find the minimum sum of elements (picked from the array) such that at least one element is picked out of every 3 consecutive elements in the array. Examples : Input : arr[] = {1, 2, 3} Output : 1 Input : arr[] = {1, 2, 3, 6, 7, 1} Output : 4 We pick 3 and 1 (3 + 1 = 4) Note that there are fol
9 min read
Find common elements in three sorted arrays
Given three sorted arrays in non-decreasing order, print all common elements in these arrays. Note: In case of duplicate common elements, print only once. Examples: Input: A[] = {1, 5, 10, 20, 30} , B[] = {5, 13, 15, 20}, C[] = {5, 20} Output: 5 20Explanation: 5 and 20 are common in all the arrays. Input: A[] = {1, 5, 10, 20, 30}, B[] = {5, 13, 15,
15+ min read
Find minimum changes required in an array for it to contain k distinct elements
Given an array arr of size N and a number K. The task is to find the minimum elements to be replaced in the array with any number such that the array consists of K distinct elements.Note: The array might consist of repeating elements. Examples: Input : arr[]={1, 2, 2, 8}, k = 1 Output : 2 The elements to be changed are 1, 8Input : arr[]={1, 2, 7, 8
6 min read
Find sum of non-repeating (distinct) elements in an array
Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};Output : 71Recommended PracticeSum of distinct el
14 min read
Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..
Given an array of integers, the task is to print the array in the order - smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on..... Examples: Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6] Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5} Input : arr[] = [1, 2, 3, 4] Output :arr[] =
7 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
Average of remaining elements after removing K largest and K smallest elements from array
Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate the average value of the remaining N - 2K elements. Examples: Input: arr = [1, 2, 4, 4, 5, 6], K = 2Output: 4Remove 2 smallest elements i.e. 1 and 2Remove 2 largest elements i.e. 5 and 6
5 min read
Practice Tags :
three90RightbarBannerImg