Given a permutation arr[] of measurement N which is unsorted and incorporates all integers from 1 to N precisely as soon as, the duty is to seek out the utmost worth of M such that performing a swap of arr[i] with arr[i+M] for any i within the vary [1, N – m] makes the array sorted.
Examples:
Enter: arr[] = {4, 2, 3, 1}
Output: 3
Clarification: Permutation might be sorted by swapping
arr[1] and arr[4], the place M = 3.
So, the utmost potential worth of M is 3.
It may be proven that we can’t type the permutation for any M > 3.Enter: arr[] = {3, 4, 2, 1}
Output: 1
Method: To unravel the issue comply with the under thought:
 Right here arr[i]_{ }and arr[i+M]_{ }are swapped for sorting.
 First verify the component at index i after which take absolute distinction of component at index i with (i+1), i.e. arr[i] and (i+1) and repeat this for all index of P array. [This denotes how much shifting we need to perform for this element]
 Then discover the best widespread divisor(GCD) of absolute variations of all components in P. The obtained worth of gcd would be the most worth of M. [Otherwise, some elements will get misplaced]
Comply with the given steps to unravel the issue:
 Discover absolutely the distinction between arr[i] and (i+1), for each i within the vary [0, N).
 Then find the greatest common divisor(GCD) of all the values found in the above step.
 The final value of GCD is the maximum possible value of M, that we can obtain.
Below is the implementation of the above approach.
C++

Java

Time Complexity: O(N * log(N))
Auxiliary Area: O(1)