Related Tags

how
find
largest number
formed
array

# How to find the largest number formed from an array of numbers

Suppose an array existsâ€‹ that contains different unsorted numbers. To form the largest number from the given numbers, sort the array in descending order and then simply combine it into one whole number.

The following illustration explains the idea better.

1 of 7

## Code

The following code extracts the largest number from the given array, sorts the array in descending order using the <greater> operator, and then converts the array into a number.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

// Function to generate largest possible
// number with given digits
int findMaxNum(int arr[], int n)
{
// sort the given array in
// descending order
sort(arr, arr+n, greater<int>());

int num = arr[0];

// generate the number
for(int i=1; i<n; i++)
{
num = num*10 + arr[i];
}

return num;
}

// Driver code
int main()
{
int arr[] = {4, 7, 9, 2, 3};

int n = sizeof(arr)/sizeof(arr[0]);

cout<<findMaxNum(arr,n);

return 0;
} 

RELATED TAGS

how
find
largest number
formed
array