You are given a permutation
of numbers from to .
A permutation , beauty, is defined as the minimum number of adjacent swaps required to sort the permutation.
If it is allowed to swap two elements of the permutation (not necessarily adjacent) at most once, then what is the minimum beauty that you can get?
Example:
Input: n=5, a[]={1,4,2,3,5}
Output: 1
Approach
Java
import java.util.ArrayList;public class SwappingNumbers {static ArrayList<Integer> arr1 = new ArrayList<>();public static void main(String args[]) {int n = 5;int arr[] = { 1, 4, 2, 3, 5 };arr1 = new ArrayList<>();System.out.println(countSwaps(arr, n));}static int merge(int arr[], int temp[], int left, int mid, int right) {int inv_count = 0;/* i is index for left subarray */int i = left;/* i is index for right subarray */int j = mid;/* i is index for resultant merged subarray */int k = left;while ((i <= mid - 1) && (j <= right)) {if (arr[i] <= arr[j])temp[k++] = arr[i++];else {temp[k++] = arr[j++];inv_count = inv_count + (mid - i);}}// Copy the remaining elements of left subarray to tempwhile (i <= mid - 1)temp[k++] = arr[i++];// Copy the remaining elements of right subarray to tempwhile (j <= right)temp[k++] = arr[j++];// Copy back the merged elements to original arrayfor (i = left; i <= right; i++)arr[i] = temp[i];return inv_count;}static int mergeSort(int arr[], int temp[], int left, int right) {int mid, inv_count = 0;if (right > left) {mid = (right + left) / 2;inv_count = mergeSort(arr, temp, left, mid);inv_count += mergeSort(arr, temp, mid + 1, right);// merge arrayinv_count += merge(arr, temp, left, mid + 1, right);}return inv_count;}static int countSwaps(int arr[], int n) {int[] left = { -1, -1 };int[] right = { 1, -1 };for (int i = 0; i < n; i++) {int d = arr[i] - (i + 1);if (d > left[0] && d != 0) {left[0] = d;left[1] = i + 1;} else if (d < right[0] && d != 0) {right[0] = d;right[1] = i + 1;}}if (left[1] != -1 && right[1] != -1) {int temp = arr[left[1] - 1];arr[left[1] - 1] = arr[right[1] - 1];arr[right[1] - 1] = temp;}return mergeSort(arr, new int[n], 0, n - 1);}}