Open In App

Maximum possible number with concatenations of K numbers from given array

Last Updated : 22 Feb, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Given an array arr[] of N integers and a positive integer K, the task is to choose K integers from the array arr[] such that their concatenation of them forms the largest possible integer. All the array elements must be chosen at least once for creating the number.

Note: It is always guaranteed that N is greater than or equal to K.

Examples:

Input: arr[] = {3, 2, 7}, K = 3
Output: 732
Explanation:
Since each array element has to be used at least once, the biggest possible number is 732.

Input: arr[] = {1, 10, 100}, K = 4
Output: 110100100

 

Approach: The above problem can be solved by sorting and converting numbers to strings. The optimal approach is to take all numbers once. After that, take the number with the most digits. In case of a tie, take the lexicographically largest number. Convert all the numbers in the string using the to_string() function. Follow the below steps to solve the problem:

Below is the implementation of the above approach:

C++
Java C# JavaScript Python3

 
 


Output: 
110100100

 


 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)


 


Next Article
Article Tags :
Practice Tags :

Similar Reads