Open In App

Greatest number that can be formed from a pair in a given Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[], the task is to find the largest number that can be formed from a pair in the given array.
Examples: 
 

Input: arr[] = { 3, 1, 9, 2 } 
Output: 93 
The pair (3, 9) leads to forming of maximum number 93
Input: arr[] = { 23, 14, 16, 25, 3, 9 } 
Output: 2523 
The pair (23, 25) leads to forming of maximum number 2523  


Approach: The idea is to form every possible pairs of the array. Then for each pair X and Y, join them as XY and YX and take the maximum out of all such pairs. 
 

for every possible in array (X, Y) ans = max(ans, XY, YX)
 


Below is the implementation of the above approach:
 

C++

// C++ implementation to find the
// greatest number from the
// given pairs of the array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the greatest
// number formed from the pairs
string getNumber(int a, int b)
{
    string X = to_string(a);
    string Y = to_string(b);
 
    // first append Y at
    // the end of X
    string XY = X + Y;
 
    // then append X at
    // the end of Y
    string YX = Y + X;
 
    // Now see which of the
    // two formed numbers
    // is greater than other
    return XY > YX ? XY : YX;
}
 
// Function to find pairs from array
void printMaxPair(int arr[], int n)
{
    int largest = INT_MIN;
 
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            int number = stoi(
                getNumber(arr[i], arr[j]));
            largest = max(largest, number);
        }
    cout << largest;
}
 
// Driver code
int main()
{
    int a[] = { 23, 14, 16, 25, 3, 9 };
    int n = sizeof(a) / sizeof(a[0]);
    printMaxPair(a, n);
    return 0;
}

                    

Java

// Java implementation to find the
// greatest number from the
// given pairs of the array
import java.util.*;
 
class GFG{
 
// Function to find the greatest
// number formed from the pairs
static String getNumber(int a, int b)
{
    String X = Integer.toString(a);
    String Y = Integer.toString(b);
 
    // First append Y at
    // the end of X
    String XY = X + Y;
 
    // Then append X at
    // the end of Y
    String YX = Y + X;
 
    // Now see which of the
    // two formed numbers
    // is greater than other
    return XY.compareTo(YX) > 0 ? XY : YX;
     
}
 
// Function to find pairs from array
static void printMaxPair(int arr[], int n)
{
    int largest = Integer.MIN_VALUE;
 
    // Iterate through all pairs
    for(int i = 0; i < n; i++)
       for(int j = i + 1; j < n; j++)
       {
          int number = Integer.parseInt(getNumber(arr[i],
                                                  arr[j]));
          largest = Math.max(largest, number);
       }
       System.out.println(largest);
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = { 23, 14, 16, 25, 3, 9 };
    int n = a.length;
     
    printMaxPair(a, n);
}
}
 
// This code is contributed by offbeat

                    

Python3

# Python3 implementation to find the
# greatest number from the
# given pairs of the array
import sys;
 
# Function to find the greatest
# number formed from the pairs
def getNumber(a, b):
 
    X = str(a);
    Y = str(b);
 
    # first append Y at
    # the end of X
    XY = X + Y;
 
    # then append X at
    # the end of Y
    YX = Y + X;
 
    # Now see which of the
    # two formed numbers
    # is greater than other
    if(XY > YX):
        return XY;
    else:
        return YX;
 
# Function to find pairs from array
def printMaxPair(arr, n):
 
    largest = -sys.maxsize - 1;
 
    # Iterate through all pairs
    for i in range(0, n):
        for j in range(i + 1, n):
            number = int(getNumber(arr[i],
                                   arr[j]));
            largest = max(largest, number);
         
    print(largest);
 
# Driver code
a = [ 23, 14, 16, 25, 3, 9 ];
n = len(a);
printMaxPair(a, n);
 
# This code is contributed by Code_Mech

                    

C#

// C# implementation to find the
// greatest number from the
// given pairs of the array
using System;
 
class GFG{
 
// Function to find the greatest
// number formed from the pairs
static String getNumber(int a, int b)
{
    String X = a.ToString();
    String Y = b.ToString();
 
    // First append Y at
    // the end of X
    String XY = X + Y;
 
    // Then append X at
    // the end of Y
    String YX = Y + X;
 
    // Now see which of the
    // two formed numbers
    // is greater than other
    return XY.CompareTo(YX) > 0 ? XY : YX;
     
}
 
// Function to find pairs from array
static void printMaxPair(int []arr, int n)
{
    int largest = int.MinValue;
 
    // Iterate through all pairs
    for(int i = 0; i < n; i++)
       for(int j = i + 1; j < n; j++)
       {
          int number = Int32.Parse(getNumber(arr[i],
                                             arr[j]));
          largest = Math.Max(largest, number);
       }
       Console.WriteLine(largest);
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 23, 14, 16, 25, 3, 9 };
    int n = a.Length;
     
    printMaxPair(a, n);
}
}
 
// This code is contributed by Amit Katiyar

                    

Javascript

<script>
 
// Javascript implementation to find the
// greatest number from the
// given pairs of the array
 
// Function to find the greatest
// number formed from the pairs
function getNumber(a, b)
{
    var X = a.toString();
    var Y = b.toString();
 
    // first append Y at
    // the end of X
    var XY = X + Y;
 
    // then append X at
    // the end of Y
    var YX = Y + X;
 
    // Now see which of the
    // two formed numbers
    // is greater than other
    return XY > YX ? XY : YX;
}
 
// Function to find pairs from array
function printMaxPair(arr, n)
{
    var largest = -100000000;
 
    // Iterate through all pairs
    for (var i = 0; i < n; i++)
        for (var j = i + 1; j < n; j++) {
            var number = parseInt(
                getNumber(arr[i], arr[j]));
            largest = Math.max(largest, number);
        }
    document.write( largest);
}
 
// Driver code
var a = [ 23, 14, 16, 25, 3, 9];
var n = a.length;
printMaxPair(a, n);
 
</script>

                    

Output
2523



Time Complexity: O(n2)

Auxiliary Space: O(1)

Approach:

  1. Sort the given array arr[] in descending order.
  2. Form a pair using the first two elements of the sorted array.
  3. Concatenate the first and second element of the pair to form a number.
  4. Continue the process of forming pairs using the remaining elements of the array until all the pairs are formed.
  5. Among all the numbers formed in step 3, find the maximum number and return it.

Below is the implementation of the above approach:

C++

// C++ implementation to find the
// greatest number from the
// given pairs of the array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find pairs from array
void printMaxPair(int arr[], int n)
{
    // Sort the array in non-increasing order
    sort(arr, arr + n, greater<int>());
 
    // Find the maximum number that can be formed from a
    // pair
    int max_num = 0;
    for (int i = 0; i < n - 1; i++) {
        int num = stoi(to_string(arr[i])
                       + to_string(arr[i + 1]));
        max_num = max(max_num, num);
    }
 
    // Print the maximum number
    cout << max_num << endl;
}
 
// Driver code
int main()
{
    int a[] = { 23, 14, 16, 25, 3, 9 };
    int n = sizeof(a) / sizeof(a[0]);
    printMaxPair(a, n);
    return 0;
}

                    

Java

import java.util.*;
 
public class GFG {
    // Function to find pairs from array
    static void printMaxPair(int[] arr, int n)
    {
        // Sort the array in non-increasing order
        Arrays.sort(arr);
        for (int i = 0; i < n / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[n - i - 1];
            arr[n - i - 1] = temp;
        }
 
        // Find the maximum number that can be formed from a
        // pair
        int max_num = 0;
        for (int i = 0; i < n - 1; i++) {
            int num = Integer.parseInt(
                Integer.toString(arr[i])
                + Integer.toString(arr[i + 1]));
            max_num = Math.max(max_num, num);
        }
 
        // Print the maximum number
        System.out.println(max_num);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] a = { 23, 14, 16, 25, 3, 9 };
        int n = a.length;
        printMaxPair(a, n);
    }
}
 
// This code is contributed by Samim Hossain Mondal.

                    

Python3

# Python implementation to find the greatest number from the given pairs of the array
 
# Function to find pairs from array
 
 
def printMaxPair(arr, n):
    # Sort the array in non-increasing order
    arr.sort(reverse=True)
 
    # Find the maximum number that can be formed from a pair
    max_num = 0
    for i in range(n - 1):
        num = int(str(arr[i]) + str(arr[i + 1]))
        max_num = max(max_num, num)
 
    # Print the maximum number
    print(max_num)
 
 
# Driver code
a = [23, 14, 16, 25, 3, 9]
n = len(a)
printMaxPair(a, n)

                    

C#

using System;
 
class Program
{
    // Function to find pairs from array
    static void PrintMaxPair(int[] arr, int n)
    {
        // Sort the array in non-increasing order
        Array.Sort(arr, (a, b) => b.CompareTo(a));
 
        // Find the maximum number that can be formed from a pair
        int max_num = 0;
        for (int i = 0; i < n - 1; i++)
        {
            int num = Convert.ToInt32(arr[i].ToString() + arr[i + 1].ToString());
            max_num = Math.Max(max_num, num);
        }
 
        // Print the maximum number
        Console.WriteLine(max_num);
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int[] a = { 23, 14, 16, 25, 3, 9 };
        int n = a.Length;
        PrintMaxPair(a, n);
    }
}

                    

Javascript

// Function to find pairs from array
function printMaxPair(arr) {
    // Sort the array in non-increasing order
    arr.sort((a, b) => b - a);
 
    // Find the maximum number that can be formed from a pair
    let maxNum = 0;
    for (let i = 0; i < arr.length - 1; i++) {
        const num = parseInt(arr[i].toString() + arr[i + 1].toString());
        maxNum = Math.max(maxNum, num);
    }
 
    // Print the maximum number
    console.log(maxNum);
}
 
// Driver code
const a = [23, 14, 16, 25, 3, 9];
printMaxPair(a);

                    

Output
2523



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



Last Updated : 20 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads