In this problem, we are given an arr[] consisting of N unsorted elements. Our task is to find the largest three elements in an array.
Let's take an example to understand the problem,
Input : arr[] = {7, 3, 9, 12, 1}
Output : 12, 9, 7Solution Approach
We basically need to find three largest elements of the array and print them. This can be done is multiple ways,
Method 1
For the largest three elements, we will create three elements holding their values, max, max2 and max3 and set these values to arr[0].
Then we will loop form i -> 1 to n-1 and for each element
if (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i].
else if (arr[i] > max2) -> max3 = max2, max2 = arr[i].
else if (arr[i] > max3) -> max3 = arr[i].
At the end of the loop, we will print all three values.
Example
Program to illustrate the working of our solution
#include <iostream>
using namespace std;
void findThreeLargestElements(int arr[], int arr_size){
int max, max2, max3;
max3 = max = max2 = arr[0];
for(int i = 0; i < arr_size; i++){
if (arr[i] > max){
max3 = max2;
max2 = max;
max = arr[i];
}
else if (arr[i] > max2){
max3 = max2;
max2 = arr[i];
}
else if (arr[i] > max3)
max3 = arr[i];
}
cout<<endl<<"Three largest elements of the array are "<<max<<", "<<max2<<", "<<max3;
}
int main(){
int arr[] = {15, 2, 7, 86, 0, 21, 50};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The array is : ";
for(int i = 0; i < n; i++)
cout<<arr[i]<<"\t";
findThreeLargestElements(arr, n);
return 0;
}Output
The array is : 15 2 7 86 0 21 50 Three largest elements of the array are 86, 50, 21
Method 2
Another method to solve the problem is by sorting the array and then printing the first three elements of the array which are three largest elements.
Algorithm
Step 1 − sort the array using a sorting technique.
Step 2 − print first three elements : arr[0] , arr[1] , arr[2]
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h>
using namespace std;
void findThreeLargestElements(int arr[], int n){
sort(arr, arr + n, std::greater<>());
int j = 0;
cout<<"\nThree largest elements are ";
for(int i = 0; i < n; i++){
if(arr[i] != arr[i+1]){
cout<<arr[i]<<" ";
j++;
}
if(j == 3){
break;
}
}
}
int main(){
int arr[] = {15, 2, 7, 86, 0, 21, 50, 53, 50};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The array is : ";
for(int i = 0; i < n; i++)
cout<<arr[i]<<"\t";
findThreeLargestElements(arr, n);
return 0;
}Output
The array is : 15 2 7 86 0 21 50 53 50 Three largest elements are 86 53 50