Find Maximum number possible by doing at-most K swaps
Given a positive integer, find the maximum integer possible by doing at-most K swap operations on its digits.
Examples:
Input: M = 254, K = 1 Output: 524
Swap 5 with 2 so number becomes 524
Input: M = 254, K = 2 Output:
542 Swap 5 with 2 so number becomes 524
Swap 4 with 2 so number becomes 542
MY CODE
public static void main(String[] args) {
int[] arr= {2,4,5};
System.out.println(MaxNum(arr,1));
}
public static int MaxNum(int[] arr, int s) {
int[] strg=new int[arr.length];
if(s<1)
return 0;
int ans=0;
for (int k = 1; k <arr.length; k++) {
strg = swap(arr, k, 0);
ans=Math.max(strg[0],arr[0]);
MaxNum(strg, s-1);
swap(arr, k, 0);
}
for(int val:strg)
System.out.print(val+". strg. ");
return ans;
}
public static int[] swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
return arr;
}
I am not sure if my approach is right . Also in above code I am not able to print full array with max number so I have just compared the 0th index (just for now).
How do I print the array with max number? please help