Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Last active September 23, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kishanjvaghela/36b1c27ecb1e22a36649d7dc465fe692 to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/36b1c27ecb1e22a36649d7dc465fe692 to your computer and use it in GitHub Desktop.
You're given an array of positive numbers. Write an algorithm that arranges these numbers one after another in a way that the end result is a single number and is the largest number possible using those combinations.
Input: {252, 11, 9, 17545}
Output: 92521754511
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
String input[] = new String[size];
for (int i = 0; i < size; i++) {
input[i] = scanner.next();
}
sortArray(input);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++) {
builder.append(input[i]);
}
System.out.println(builder.toString());
}
public static void sortArray(String[] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length - i-1; j++) {
if (isLarge(input[j], input[j + 1])) {
String temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
}
}
public static boolean isLarge(String s1, String s2) {
String num1 = s1+s2;
String num2 = s2+s1;
return num1.compareTo(num2) < 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment