Compute nearest larger number by interchanging digits updated.
Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1.
import java.util.Arrays;
import java.util.Scanner;
class Test {
static int ans = Integer.MAX_VALUE;
static void f(char[] a, String s, int r, boolean[] vis, int b) {
// System.out.println(s);
if (r == 0) {
int x = Integer.parseInt(s);
if (x > b && x < ans)
ans = Math.min(x, ans);
return;
}
for (int i = 0; i < a.length; i++) {
if (!vis[i]) {
s += a[i];
vis[i] = true;
f(a, s, r - 1, vis, b);
s = s.substring(0, s.length() - 1);
vis[i] = false;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] a = sc.next().toCharArray();
// System.out.println(Arrays.toString(a));
boolean[] vis = new boolean[a.length];
int b = sc.nextInt();
f(a, "", a.length, vis, b);
System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);
}
}
This is the working solution but how Can I make it fast. I will be glad if you give any suggestions.