Problem Statement: JNEXT
DevG was challanged to find the just next greater number which can be formed using digits of a given number. Now DevG needs your help to find that just next greater number and win the challenge.
Input
The first line have t number of test cases (1 <= t <= 100). In next 2*t lines for each test case first there is number n (1 <= n <= 1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.
Output
Print the just next greater number if possible else print -1 in one line for each test case.
Note : There will be no test case which contains zero in starting digits of any given number.
Example
Input:
2 5 1 5 4 8 3 10 1 4 7 4 5 8 4 1 2 6
Output:
15834 1474584162
My Solution is
public static void main(String[] argh) throws Exception{
Reader br = new Reader();
int t= br.nextInt();
for(int aa=0; aa<t; aa++){
int n= br.nextInt();
int[] arr= new int[n];
int breakPoint= -1;
int mI= -1;
for(int qq=0; qq<n; qq++){
arr[qq]= br.nextInt();
if(qq !=0 && arr[qq] > arr[qq-1]){
breakPoint= qq-1;
}
if(breakPoint != -1){
if(arr[breakPoint] < arr[qq]){
mI= qq;
}
}
}
if(breakPoint == -1 || n == 1){
System.out.println(-1);
continue;
}
// swap
arr[breakPoint]= arr[breakPoint] + arr[mI];
arr[mI]= arr[breakPoint] - arr[mI];
arr[breakPoint]= arr[breakPoint] - arr[mI];
breakPoint++;
for(int ii=0; ii<breakPoint; ii++){
System.out.print(arr[ii]);
}
for(int ii=n-1; ii>=breakPoint; ii--){
System.out.print(arr[ii]);
}
System.out.println("");
}
}
My solution is having O(N) time complexity but still I am getting TLE. Can anyone point out issue?