×

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that all the elements contribute to make the largest number. Also, return the largest formed number in string format because the number can be very large.

For example

Test case 1

N = 5

Arr[] = {5, 9, 30, 3, 34}

Output = 9534330

Explanation

The largest value formed with the arrangement of 9,5,34,3,30.

Test case 2

N = 4

Arr[] = {60, 546, 548, 54}

Output = 6054854654

Explanation

The largest value formed with the arrangement of 60,548,546,54.

Brute-force approach

A simple approach is to sort the array and form a string in order to make a largest number. The array sorted in descending order using bubble sort does not work here.

For example, if we take 548, it is greater than 60 but after sorting 60 comes before.

Similarly, 98 is greater than 9 but after sorting it comes after.

Below is the code implementation.

Code

#include <algorithm>

#include <iostream>

#include <string>

#include <vector>

#include<bits/stdc++.h>

using namespace std;


string number(vector<int>& nums){ // declare a function

  if( nums[0]==0 && nums[nums.size()-1] == 0) // if array contains 0

return "0";

        vector<string> result;

          // push array element to string vector

        for(auto x:nums){

            result.push_back(to_string(x));

        }

          // Sort the result vector

        for(int i=0;i<nums.size()-1;i++){

            for(int j=0;j<nums.size()-i-1;j++){

                if(result[j]+result[j+1]<result[j+1]+result[j]){

                    swap(result[j],result[j+1]);

                }

            }

        }

          // Append it to ans string

        string ans="";

        for(int i=0;i<result.size();i++){

            ans+=result[i];

        }

        return ans; // print ans

}

int main()

{

          vector<int> arr;

          arr.push_back(54);

          arr.push_back(546);

          arr.push_back(548);

          arr.push_back(60);

cout  << number(arr);

          return 0;

}

Output

6054854654

Time complexity

O(n*n)

Space complexity

O(1)

Comparison based sorting

The problem occurred in the brute force approach will be covered in this approach. While sorting the array, we will modify the default compare function according to our needs.

The function my_compare() will work in this way.

This function will compare two numbers X and Y. If the formation of XY is greater then X will come first in the sorting order otherwise Y will come in the sorting order.

For example, if we have x as 541 and Y as 60. We compare 54160 and 60541. The greater one is 60541 so Y remains first.

Code

#include <algorithm>

#include <iostream>

#include <string>

#include <vector>

#include<bits/stdc++.h>

using namespace std;


int my_Compare(int X, int Y)

{

string x1= to_string(X); // x is  convert to string

    string y1 =to_string(Y); // y is  convert to string

         

          string XY = x1.append(y1); // Make combination of XY by append X to Y


          string YX = y1.append(x1); // Make combination of YX by append Y to X

     

          return XY.compare(YX) > 0 ? 1 : 0; // Compare for the greater one

}


void printLargest(vector<int> arr)

{
       

          sort(arr.begin(), arr.end(), my_Compare); // Sort the arr by using my_Compare

          for (int i = 0; i < arr.size(); i++)

                   cout << arr[i]; // Print the array arranged in form of largest number

}

int main()

{

          vector<int> arr; // make a vector

          arr.push_back(54);

          arr.push_back(546);

          arr.push_back(548);

          arr.push_back(60);

          printLargest(arr);

        return 0;

}

Output

6054854654

Time complexity

O(nlogn)

Space complexity

O(n)

Using itertools

If we want to do this problem using Python, a module itertools.combination() is used to find all the combinations of an array.

For example

Input : arr[] = [1, 2, 3, 4],

            r = 2

Output : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

Here r is the length of a set of sequences that can be formed.

Now this module can be applied to our array. We can find all the possible combinations of the array and make a string of a particular sequence set.

Finally, we will get the largest string.

Code

#import itertools from permutations

from itertools import permutations

def largest(l): # function to print largest number formed

    lst = [] #an array to store the result

    for i in permutations(l, len(l)):

        # provides all permutations of the list values,

        # store them in list to find max

        lst.append("".join(map(str,i)))

    return max(lst) # return max of the lst

print(largest([54, 546, 548, 60])) # Call largest function

Output

6054854654

Related Topics

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.