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:
- Initialize an empty string res to store the answer.
- Sort the array numbers[] in ascending order.
- Initialize a vector of strings v[].
- Iterate over the range [0, K) using the variable i and push the string number numbers[i] into the vector v[].
- Decrease the value of N by K and push the value numbers[K-1] N times into the vector v[].
- Sort the vector v[] using the comparator function.
- Iterate over the range [v.size()-1, 0] using the variable i and add the value v[i] to the variable res.
- After performing the above steps, print the value of res as the answer.
Below is the implementation of the above approach:
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;
// Custom comparator function bool str_cmp(string s1, string s2)
{ return (s1 + s2 < s2 + s1);
} // Function to get the largest possible // string string largestNumber(vector< int > 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<string> 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 Code int main()
{ vector< int > arr = { 1, 10, 100 };
int K = 4;
cout << largestNumber(arr, K);
return 0;
} |
// Java program for the above approach import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{ // Custom comparator function
static int str_cmp(String s1, String s2)
{
return (s1 + s2).compareTo(s2 + s1);
}
// Function to get the largest possible
// String
static String largestNumber( int arr[], int K)
{
int N = arr.length;
// Initialize a new variable which
// will store the answers.
String res = "" ;
// Sort the numbers array in
// non-decreasing order
Arrays.sort(arr);
// Stores the array element which will
// be used to construct the answer
ArrayList<String> v = new ArrayList<String>();
// Take all numbers atleast once
for ( int i = 0 ; i < N; i++) {
v.add(String.join( "" ,Integer.toString(arr[i])));
}
K -= N;
// Take the largest digits number
// for remaining required numbers
while (K > 0 ) {
v.add(String.join( "" ,Integer.toString(arr[N - 1 ])));
K--;
}
// Sort the readonly answer according to
// the comparator function.
v.sort((s1,s2) -> str_cmp(s1,s2));
for ( int i = v.size() - 1 ; i >= 0 ; i--)
res += v.get(i);
return res;
}
// Driver Code
public static void main(String[] args) {
int arr[] = { 1 , 10 , 100 };
int K = 4 ;
System.out.print(largestNumber(arr, K));
}
} // This code is contributed by Pushpesh Raj. |
// C# program for the above approach using System;
using System.Collections.Generic;
public class GFG
{ // Custom comparator function
// Function to get the largest possible
// String
static String largestNumber( int [] arr, int K)
{
int N = arr.Length;
// Initialize a new variable which
// will store the answers.
String res = "" ;
// Sort the numbers array in
// non-decreasing order
Array.Sort(arr);
// Stores the array element which will
// be used to construct the answer
List<String> v = new List<String>();
// Take all numbers atleast once
for ( int i = 0; i < N; i++) {
v.Add(String.Join( "" ,arr[i]));
}
K -= N;
// Take the largest digits number
// for remaining required numbers
while (K > 0) {
v.Add(String.Join( "" ,arr[N - 1]));
K--;
}
// Sort the readonly answer according to
// the comparator function.
v.Sort((s1,s2) => (s1 + s2).CompareTo(s2 + s1));
for ( int i = v.Count - 1; i >= 0; i--)
res += v[i];
return res;
}
// Driver Code
public static void Main(String[] args) {
int [] arr = { 1, 10, 100 };
int K = 4;
Console.Write(largestNumber(arr, K));
}
} // This code is contributed by Rajput-Ji |
<script> // JavaScript Program to implement
// the above approach
// Function to get the largest possible
// string
function largestNumber(arr,
K) {
let N = arr.length;
// Initialize a new variable which
// will store the answers.
let res = "" ;
// Sort the numbers array in
// non-decreasing order
arr.sort( function (a, b) { return a - b })
// Stores the array element which will
// be used to construct the answer
let v = [];
// Take all numbers atleast once
for (let i = 0; i < N; i++) {
v.push(arr[i].toString());
}
K -= N;
// Take the largest digits number
// for remaining required numbers
while (K) {
v.push(arr[N - 1].toString());
K--;
}
// Sort the final answer according to
// the comparator function.
v.sort( function (s1, s2) { return parseInt(s1 + s2) - parseInt(s2 + s1) });
for (let i = v.length - 1; i >= 0; i--)
res += v[i];
return res;
}
// Driver Code
let arr = [1, 10, 100];
let K = 4;
document.write(largestNumber(arr, K));
// This code is contributed by Potta Lokesh
</script>
|
# Python program for the above approach def largestNumber(arr, K):
# Initialize a new variable which
# will store the answers.
res = ""
# Sort the numbers array in
# non-decreasing order
arr.sort()
# Stores the array element which will
# be used to construct the answer
v = []
# Take all numbers at least once
for i in range ( len (arr)):
v.append( str (arr[i]))
K - = len (arr)
# Take the largest digits number
# for remaining required numbers
while K > 0 :
v.append( str (arr[ - 1 ]))
K - = 1
# Sort the readonly answer according to
# the comparator function.
v.sort(key = lambda x: x * 3 , reverse = True )
res = ''.join(v)
return res
# Driver Code arr = [ 1 , 10 , 100 ]
K = 4
print (largestNumber(arr, K))
|
110100100
Time Complexity: O(N*log N)
Auxiliary Space: O(N)