Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543
I told solution in $O(n logn)$. He asked me optimize
The following greedy code does this in O(n) time. Where n is the number of digits in the number.
int num = 8756404;
int[] times = new int[10];
while(true){
if(num==0){
break;
}
int val = num%10;
times[val]++;
num /= 10;
}
for(int i=9; i>=0; i--){
for(int j=0; j<times[i]; j++){
System.out.print(i);
}
}
It works by counting the number of occurences of each of the digits in the input number. Then printing each number the number of times it was in the input number in reverse order, ie. starting from 9 to 0.
RunTime: 00:00:00.01
public int Assignment(int number)
{
// Consider that int.MaxValue equals to 2147483647
var siblingString = String.Join("", number.ToString().ToCharArray().OrderByDescending(n => n));
int sibling = -1;
if (!int.TryParse(siblingString, out sibling) || sibling > 100000000)
{
return -1;
}
return sibling;
}
Performances tested with the following code:
static void Main()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var result = AssignmentOne(2147483646);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}