Decode The Code

Mr. Seth and his friend are on a secret mission to infiltrate the terrorist organization. He has to pass the last security point by entering N digit passcode. His friend has successfully got the digits of the passcode but they are not in the correct order. In his college time, he was taught Automata by a brilliant professor at his college. So, he decided to design a machine that can arrange the digits correctly to unlock the last point. It was known to Mr. Seth that the correct passcode is the lexicographically the largest combination of these digits. Now the machine can only swap K adjacent digits.

Mr. Seth does not have much time, so he requires your help to operate the machine correctly.

Example:

Input: n=5, l=3,  arr[] = { 3, 5, 1, 2, 1 };
Output: 53211

Approach

Java


public class DecodeTheCode {
    public static void main(String args[]) {
        int n = 5;
        int l = 3;
        int arr[] = { 35121 };
        int j = 0;
        while (l > 0 && j < arr.length) {
            int max = getMax(arr, arr.length, j, j + l + 1);
            while (l > 0 && max > 0 && arr[max] > arr[max - 1]) {
                l--;
                int tmp = arr[max - 1];
                arr[max - 1] = arr[max];
                arr[max] = tmp;
                max--;
            }
            j++;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(arr[i]);
        }
        System.out.println(sb);
    }

    static int getMax(int[] arrint nint startint end) {
        int m = start;
        for (int i = start + 1; i < end && i < n; i++) {
            if (arr[m] < arr[i]) {
                m = i;
            }
        }
        return m;
    }
}


No comments:

Post a Comment