Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value.
A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but 9 comes before 98 in output.
So how do we go about it? The idea is to use any comparison based sorting algorithm.
In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers.
For Python, the procedure is explained in largestNumber() function.
Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Following is the implementation of the above approach.
To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array.
Below is the implementation of the above approach:
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int myCompare(string X, string Y)
{
string XY = X.append(Y);
string YX = Y.append(X);
return XY.compare(YX) > 0 ? 1 : 0;
}
void printLargest(vector<string> arr)
{
sort(arr.begin(), arr.end(), myCompare);
for ( int i = 0; i < arr.size(); i++)
cout << arr[i];
}
int main()
{
vector<string> arr;
arr.push_back( "54" );
arr.push_back( "546" );
arr.push_back( "548" );
arr.push_back( "60" );
printLargest(arr);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printLargest(Vector<String> arr)
{
Collections.sort(arr, new Comparator<String>()
{
@Override public int compare(String X, String Y)
{
String XY = X + Y;
String YX = Y + X;
return XY.compareTo(YX) > 0 ? - 1 : 1 ;
}
});
Iterator it = arr.iterator();
while (it.hasNext())
System.out.print(it.next());
}
public static void main(String[] args)
{
Vector<String> arr;
arr = new Vector<>();
arr.add( "54" );
arr.add( "546" );
arr.add( "548" );
arr.add( "60" );
printLargest(arr);
}
}
|
Python3
def largestNumber(array):
if len (array) = = 1 :
return str (array[ 0 ])
for i in range ( len (array)):
array[i] = str (array[i])
for i in range ( len (array)):
for j in range ( 1 + i, len (array)):
if array[j] + array[i]>array[i] + array[j]:
array[i],array[j] = array[j],array[i]
result = ''.join(array)
if (result = = '0' * len (result)):
return '0'
else :
return result
if __name__ = = "__main__" :
a = [ 54 , 546 , 548 , 60 ]
print (largestNumber(a))
|
C#
using System.Collections.Generic;
using System;
namespace LargestNumberClass {
class LargestNumberClass {
public static void
LargestNumberMethod(List< int > inputList)
{
string output = string .Empty;
List< string > newList = inputList.ConvertAll< string >(
delegate ( int i) { return i.ToString(); });
newList.Sort(MyCompare);
for ( int i = 0; i < inputList.Count; i++)
{
output = output + newList[i];
}
if (output[0] == '0' && output.Length > 1)
{
Console.Write( "0" );
}
Console.Write(output);
}
internal static int MyCompare( string X, string Y)
{
string XY = X + Y;
string YX = Y + X;
return XY.CompareTo(YX) > 0 ? -1 : 1;
}
}
class Program {
static void Main( string [] args)
{
List< int > inputList
= new List< int >() { 54, 546, 548, 60 };
LargestNumberClass.LargestNumberMethod(inputList);
}
}
}
|
PHP
<?php
function myCompare( $X , $Y )
{
$XY = $Y . $X ;
$YX = $X . $Y ;
return strcmp ( $XY , $YX ) > 0 ? 1: 0;
}
function printLargest( $arr )
{
usort( $arr , "myCompare" );
for ( $i = 0; $i < count ( $arr ) ; $i ++ )
echo $arr [ $i ];
}
$arr = array ( "54" , "546" , "548" , "60" );
printLargest( $arr );
?>
|
Javascript
<script>
function myCompare(X, Y)
{
let XY = X + Y;
let YX = Y + X;
return (YX - XY)
}
function printLargest(arr)
{
arr.sort(myCompare);
for (let i = 0; i < arr.length; i++)
document.write(arr[i])
document.write(arr.join( "" ))
}
let arr = [];
arr.push( "54" );
arr.push( "546" );
arr.push( "548" );
arr.push( "60" );
printLargest(arr);
</script>
|
Time Complexity: O(n log n)
Auxiliary Space: O(X), Where X is the maximum number of digits in the given numbers.
In the above solution, we are allowed strings inputs but in case strings are restricted then also we can solve above problem using long long int to find biggest arrangement. The only limitation is that we can not store numbers greater than 10^18. In case it exceeds that the above solution will be the only option.
C++14
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
static bool myCompare( int x, int y)
{
int xy = x, yx = y;
int countx = 0, county = 0;
while (x > 0) {
countx++;
x /= 10;
}
while (y > 0) {
county++;
y /= 10;
}
x = xy;
y = yx;
while (countx--)
yx *= 10;
while (county--)
xy *= 10;
yx += x;
xy += y;
return xy > yx;
}
void printLargest(vector<ll> arr)
{
sort(arr.begin(), arr.end(), myCompare);
for ( int i = 0; i < arr.size(); i++)
cout << arr[i];
}
int main()
{
vector<ll> arr;
arr.push_back(54);
arr.push_back(546);
arr.push_back(548);
arr.push_back(60);
printLargest(arr);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static void printLargest(ArrayList<Integer> arr)
{
Collections.sort(arr, new Comparator<Integer>(){
@Override
public int compare(Integer x, Integer y)
{
int xy = x;
int yx = y;
int countx = 0 ;
int county = 0 ;
while (x > 0 ) {
countx++;
x /= 10 ;
}
while (y > 0 ) {
county++;
y /= 10 ;
}
x = xy;
y = yx;
while (countx > 0 )
{
countx--;
yx *= 10 ;
}
while (county > 0 )
{
county--;
xy *= 10 ;
}
yx += x;
xy += y;
return -xy + yx;
}
});
for ( int i = 0 ; i < arr.size(); i++)
System.out.print(arr.get(i));
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>();
arr.add( 54 );
arr.add( 546 );
arr.add( 548 );
arr.add( 60 );
printLargest(arr);
}
}
|
Python3
import functools
def myCompare(x, y):
xy = x
yx = y
countx = 0
county = 0
while (x > 0 ):
countx + = 1
x / / = 10
while (y > 0 ):
county + = 1
y / / = 10
x = xy
y = yx
while (countx):
countx - = 1
yx * = 10
while (county):
county - = 1
xy * = 10
yx + = x
xy + = y
return 1 if xy > yx else - 1
def printLargest(arr):
arr.sort(key = functools.cmp_to_key(myCompare))
arr.reverse()
print ("".join( map ( str , arr)))
arr = [ 54 , 546 , 548 , 60 ]
printLargest(arr)
|
C#
using System;
using System.Collections.Generic;
class myCompare : Comparer< int >
{
public override int Compare( int x, int y)
{
int xy = x;
int yx = y;
int countx = 0;
int county = 0;
while (x > 0) {
countx++;
x /= 10;
}
while (y > 0) {
county++;
y /= 10;
}
x = xy;
y = yx;
while (countx > 0) {
countx--;
yx *= 10;
}
while (county > 0) {
county--;
xy *= 10;
}
yx += x;
xy += y;
return -xy + yx;
}
};
public class GFG {
static void printLargest(List< int > arr)
{
arr.Sort( new myCompare());
for ( int i = 0; i < arr.Count; i++)
Console.Write(arr[i]);
}
public static void Main( string [] args)
{
List< int > arr = new List< int >();
arr.Add(54);
arr.Add(546);
arr.Add(548);
arr.Add(60);
printLargest(arr);
}
}
|
Javascript
function myCompare(x, y)
{
let xy = x;
let yx = y;
let countx = 0;
let county = 0;
while (x > 0) {
countx++;
x = Math.floor(x / 10);
}
while (y > 0) {
county++;
y = Math.floor(y / 10);
}
x = xy;
y = yx;
while (countx--)
yx *= 10;
while (county--)
xy *= 10;
yx += x;
xy += y;
return xy < yx;
}
function printLargest(arr)
{
arr.sort(myCompare);
for ( var i = 0; i < arr.length; i++)
process.stdout.write(arr[i].toString());
}
let arr = [];
arr.push(54);
arr.push(546);
arr.push(548);
arr.push(60);
printLargest(arr);
|
Time Complexity: O(n logn) , sorting is considered to have a running time complexity of O(n logn), and the for loop runs in O(n) time.
Auxiliary Space: O(1)
Another approach:(using itertools)
Using the inbuilt library of Python, itertools library can be used to perform this task.
C++
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
string largest(vector< int > l)
{
vector<string> lst;
sort(l.begin(),
l.end());
do {
string s = "" ;
for ( int i = 0; i < l.size(); i++) {
s += to_string(
l[i]);
}
lst.push_back(s);
} while (next_permutation(
l.begin(),
l.end()));
return *max_element(lst.begin(), lst.end());
}
int main()
{
vector< int > v = { 54, 546, 548, 60 };
cout << largest(v) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static String largest(ArrayList<Integer> l)
{
ArrayList<String> lst = new ArrayList<String>();
Collections.sort(
l);
do {
String s = "" ;
for ( int i = 0 ; i < l.size(); i++) {
s += Integer.toString(l.get(
i));
}
lst.add(s);
} while (
nextPermutation(l));
return Collections.max(lst);
}
static boolean nextPermutation(ArrayList<Integer> nums)
{
int i = nums.size() - 2 ;
while (i >= 0 && nums.get(i) >= nums.get(i + 1 )) {
i--;
}
if (i < 0 ) {
return false ;
}
int j = nums.size() - 1 ;
while (nums.get(j) <= nums.get(i)) {
j--;
}
Collections.swap(nums, i, j);
Collections.reverse(
nums.subList(i + 1 , nums.size()));
return true ;
}
public static void main(String[] args)
{
ArrayList<Integer> v = new ArrayList<Integer>(
Arrays.asList( 54 , 546 , 548 , 60 ));
System.out.println(
largest(v));
}
}
|
Python3
from itertools import permutations
def largest(l):
lst = []
for i in permutations(l, len (l)):
lst.append("".join( map ( str ,i)))
return max (lst)
print (largest([ 54 , 546 , 548 , 60 ]))
|
Javascript
function largest(l) {
let lst = [];
l.sort();
do {
let s = "" ;
for (let i = 0; i < l.length; i++) {
s += l[i].toString();
}
lst.push(s);
} while (nextPermutation(l));
return Math.max(...lst);
}
function nextPermutation(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false ;
}
let j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
[arr[i], arr[j]] = [arr[j], arr[i]];
let left = i + 1;
let right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return true ;
}
let v = [54, 546, 548, 60];
console.log(largest(v));
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static string Largest(List< int > l)
{
var lst = new List< string >();
l.Sort();
do
{
var s = string .Join( "" , l.Select(i => i.ToString()));
lst.Add(s);
} while (NextPermutation(l));
return lst.Max();
}
static bool NextPermutation(List< int > nums)
{
int i = nums.Count - 2;
while (i >= 0 && nums[i] >= nums[i + 1])
{
i--;
}
if (i < 0)
{
return false ;
}
int j = nums.Count - 1;
while (nums[j] <= nums[i])
{
j--;
}
nums.Swap(i, j);
nums.Reverse(i + 1, nums.Count - (i + 1));
return true ;
}
public static void Main( string [] args)
{
var v = new List< int >() { 54, 546, 548, 60 };
Console.WriteLine(Largest(v));
}
}
public static class Extensions
{
public static void Swap<T>( this IList<T> list, int i, int j)
{
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
public static void Reverse<T>( this IList<T> list, int index, int count)
{
int i = index, j = index + count - 1;
while (i < j)
{
list.Swap(i++, j--);
}
}
}
|
Time Complexity: O(n!)
Auxiliary Space: O(1).
This article is compiled by Ravi Chandra Enaganti and improved by prophet1999. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.