Open In App

Maximize M such that swapping arr[i] with arr[i+M] makes Array sorted

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a permutation arr[] of size N which is unsorted and contains all integers from 1 to N exactly once, the task is to find the maximum value of M such that performing a swap of arr[i] with arr[i+M] for any i in the range [1, N-M] makes the array sorted.

Examples: 

Input:  arr[] = {4, 2, 3, 1}
Output: 3
Explanation: Permutation can be sorted by swapping 
arr[1] and arr[4], where M = 3. 
So, the maximum possible value of M is 3. 
It can be shown that we cannot sort the permutation for any M > 3.

Input: arr[] = {3, 4, 2, 1}

Output: 1

 

Approach: To solve the problem follow the below idea:

  • Here arr[i] and arr[i+M]  are swapped for sorting. 
  • First check the element at index i and then take absolute difference of element 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 find the greatest common divisor(GCD) of absolute differences of all elements in P. The obtained value of gcd will be the maximum value of M. [Otherwise, some elements will get misplaced]

Follow the given steps to solve the problem:

  • Find the absolute difference between arr[i] and (i+1), for every i in the range [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++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to find the maximum value of m
int maxValue(int P[], int N)
{
    int res = 0;
 
    for (int i = 0; i < N; i++) {
        res = gcd(res, abs(P[i] - (i + 1)));
    }
    return res;
}
 
// Driver code
int main()
{
    int P[] = { 4, 2, 3, 1 };
    int N = sizeof(P) / sizeof(P[0]);
 
    // Function call
    cout << maxValue(P, N);
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
 
    // Function to find the maximum value of M
    public static int maxVal(int P[], int N)
    {
        int res = 0;
        for (int i = 0; i < N; i++) {
            int diff = P[i] - (i + 1);
            int x = Math.abs(diff);
            res = gcd(res, x);
        }
        return res;
    }
    // Driver code
    public static void main(String[] args)
    {
        int P[] = { 4, 2, 3, 1 };
        int N = P.length;
 
        // Function call
        System.out.println(maxVal(P, N));
    }
}


Python3




# Python3 code to implement the approach
 
# Recursive function to return gcd of a and b
def gcd(a, b):
    if(b == 0):
        return abs(a)
    else:
        return gcd(b, a % b)
       
# Function to find the maximum value of M      
def maxValue(P,N):
  res = []
  for i in range(N):
     if abs((P[i]-1)-i) > 0:
         res.append(abs((P[i]-1)-i))
  answer =  res[0]
  for i in range(len(res)-1):
      answer = gcd(answer,res[i+1])
  return answer
 
# Driver code
P = [ 4, 2, 3, 1 ]
N=len(P)
print(maxValue(P,N))
 
# This code is contributed by aarohirai2616.


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
 
    // Function to find the maximum value of M
    public static int maxVal(int []P, int N)
    {
        int res = 0;
        for (int i = 0; i < N; i++) {
            int diff = P[i] - (i + 1);
            int x = Math.Abs(diff);
            res = gcd(res, x);
        }
        return res;
    }
    // Driver code
    public static void Main(string[] args)
    {
        int []P = { 4, 2, 3, 1 };
        int N = P.Length;
 
        // Function call
        Console.WriteLine(maxVal(P, N));
    }
}
 
// This code is contributed by AnkThon


Javascript




<script>
        // JavaScript code to implement the approach
 
 
        // Recursive function to return gcd of a and b
        const gcd = (a, b) => {
            if (b == 0)
                return a;
            return gcd(b, a % b);
        }
 
        // Function to find the maximum value of m
        const maxValue = (P, N) => {
            let res = 0;
 
            for (let i = 0; i < N; i++) {
                res = gcd(res, Math.abs(P[i] - (i + 1)));
            }
            return res;
        }
 
        // Driver code
 
        let P = [4, 2, 3, 1];
        let N = P.length;
 
        // Function call
        document.write(maxValue(P, N));
 
        // This code is contributed by rakeshsahni
 
    </script>


Output

3

Time Complexity: O(N * log(N))
Auxiliary Space: O(log (min(a,b)))



Similar Reads

Count pairs (i, j) from an array such that |arr[i]| and |arr[j]| both lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|
Given an array arr[] of size N, the task is to count the number of pairs (arr[i], arr[j]) such that |arr[i]| and |arr[j]| lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|. Examples: Input: arr[] = {1, 3, 5, 7} Output: 2 Explanation: Pair (arr[1], arr[2]) (= (3, 5)) lies between |3 - 5| (= 2) and |3 + 5| (= 8).Pair (arr[2], arr[3]) (= (5, 7)) li
6 min read
Check whether (i,j) exists such that arr[i] != arr[j] and arr[arr[i]] is equal to arr[arr[j]]
Given an array A[]. The task is to determine if it is possible to choose two indices 'i' and 'j' such that the below conditions gets satisfied:- A[i] is not equal to A[j].A[A[i]] is equal to A[A[j]]. Note: The value of the elements in an array is less than the value of N i.e. For every i, arr[i] &lt; N. Examples: Input: N = 4, A[] = {1, 1, 2, 3} Ou
10 min read
Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n
Given an array arr[] of size n whose elements are from the range [1, n]. The task is to find maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]|. You can arrange the numbers in the array in any order. Examples: Input: arr[] = {1, 2, 3, 4} Output: 7 Arrange the array in this way for max value, arr[] = {3, 1, 4, 2}
3 min read
Minimize last remaining element of Array by selecting pairs such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j]
Given an array arr[] of N positive integers, the task is to find the smallest possible value of the last remaining element in the array after performing the following operations any number of times: Select a pair of indices (i, j) such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j].If an array element arr[i] &lt;= 0, remove it fro
5 min read
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l. Find the maximum value of arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l Example: Let us say our array is {4, 8, 9, 2, 20} Then the maximum such value is 23 (9 - 4 + 20 - 2)Recommended PracticeMaximum valueTry It! Brute Force Method: We can simply fin
11 min read
Count pairs in an array such that LCM(arr[i], arr[j]) &gt; min(arr[i],arr[j])
Given an array arr[], the task is to find the count of pairs in the array such that LCM(arr[i], arr[j]) &gt; min(arr[i], arr[j]) Note: Pairs (arr[i], arr[j]) and (arr[j], arr[i]) are considered identical and will be counted only once. Examples: Input: arr[] = {1, 1, 4, 9} Output: 5 All valid pairs are (1, 4), (1, 9), (1, 4), (1, 9) and (4, 9). Inpu
9 min read
Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
11 min read
Count quadruples (i, j, k, l) in an array such that i &lt; j &lt; k &lt; l and arr[i] = arr[k] and arr[j] = arr[l]
Given an array arr[] consisting of N integers, the task is to count the number of tuples (i, j, k, l) from the given array such that i &lt; j &lt; k &lt; l and arr[i] = arr[k] and arr[j] = arr[l]. Examples: Input: arr[] = {1, 2, 1, 2, 2, 2} Output: 4 Explanation: The tuples which satisfy the given condition are: 1) (0, 1, 2, 3) since arr[0] = arr[2
6 min read
C++ Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Java Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Article Tags :
Practice Tags :