Maximum possible number with concatenations of K numbers from given array

• Last Updated : 06 Oct, 2021

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 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++

 // C++ program for the above approach #include using namespace std; // Custom comparator functionbool str_cmp(string s1, string s2){    return (s1 + s2 < s2 + s1);} // Function to get the largest possible// stringstring largestNumber(vector arr,                     int K){    int N = arr.size();     // Initialize a new variable which    // will store the answers.    string res = "";     // Sort the numbers array in    // non-decreasing order    sort(arr.begin(), arr.end());     // Stores the array element which will    // be used to construct the answer    vector v;     // Take all numbers atleast once    for (int i = 0; i < N; i++) {        v.push_back(to_string(arr[i]));    }    K -= N;     // Take the largest digits number    // for remaining required numbers    while (K) {        v.push_back(to_string(arr[N - 1]));        K--;    }     // Sort the final answer according to    // the comparator function.    sort(v.begin(), v.end(), str_cmp);    for (int i = v.size() - 1; i >= 0; i--)        res += v[i];     return res;} // Driver Codeint main(){    vector arr = { 1, 10, 100 };    int K = 4;    cout << largestNumber(arr, K);     return 0;}

Javascript



Output:
110100100

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

My Personal Notes arrow_drop_up