Open In App

Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] consisting of distinct elements, the task is to obtain the largest possible modulus value that remains after repeatedly replacing adjacent elements by their modulus, starting from the first element, for any possible permutations of the given array.

 (…(( A[1] mod A[2]) mod A[3]) …. ) mod A[N])

Examples:

Input: A[] = {7, 10, 12}
Output: 7
Explanation: All possible values of the given expression across all permutations of the given array are as follows:
{7, 10, 12} = ((7 % 10) % 12) = 7
{10, 12 7} = ((10 % 12) % 7) = 3
{7, 12, 10} =((7 % 12) % 10) = 7
{10, 7, 12} = ((10 % 7) % 12) = 3
{12, 7, 10} = ((12 % 7) % 10) = 5
{12, 10, 7} = ((12 % 10) % 7) = 2
Therefore, the maximum possible value is 7.

Input: A[] = {20, 30}
Output: 20
Explanation:
The maximum possible value from all the permutations of the given array is 20.

Naive Approach: The simplest approach to solve the problem is to generate all permutations of the given array and find the value of the given expression for all permutations. Finally, print the maximum value of the expression obtained. 
Time Complexity: O(N * N!) 
Auxiliary Space: O(N)

Efficient Approach: To optimize the above approach, the following observations need to be made:

  • For any permutation A1…..AN, the value of the expression always lies in the range [0, min(A2…..An)-1].
  • Considering K to be the smallest element in the array, the value of the expression will always be K for the permutations having K as the first element.
  • For all other permutations, the value of the expression will always be less than K, as shown in the examples above. Therefore, K is the maximum possible value of the expression for any permutation of the array.
  • Therefore, the maximum possible value will always be equal to the smallest element of the array.

Therefore, to solve the problem, simply traverse the array and find the minimum element present in the array and print it as the required answer.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// of two numbers
int min(int a, int b)
{
    return (a > b) ? b : a;
}
 
// Function to find the maximum value
// possible of the given expression
// from all permutations of the array
int maximumModuloValue(int A[], int n)
{
    // Stores the minimum value
    // from the array
    int mn = INT_MAX;
    for (int i = 0; i < n; i++) {
        mn = min(A[i], mn);
    }
 
    // Return the answer
    return mn;
}
 
// Driver Code
int main()
{
    int A[] = { 7, 10, 12 };
 
    int n = (sizeof(A) / (sizeof(A[0])));
 
    cout << maximumModuloValue(A, n)
         << endl;
 
    return 0;
}


Java




// Java Program to implement
// the above approach
import java.io.*;
class GFG{
 
    // Function to find the maximum value
    // possible of the given expression
    // from all permutations of the array
    static int maximumModuloValue(int A[], int n)
    {
        // Stores the minimum value
        // from the array
        int mn = Integer.MAX_VALUE;
 
        for (int i = 0; i < n; i++)
        {
            mn = Math.min(A[i], mn);
        }
 
        // Return the answer
        return mn;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = {7, 10, 12};
        int n = A.length;
        System.out.println(maximumModuloValue(A, n));
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 program to implement
# the above approach
import sys
 
# Function to find the maximum value
# possible of the given expression
# from all permutations of the array
def maximumModuloValue(A, n):
 
    # Stores the minimum value
    # from the array
    mn = sys.maxsize
    for i in range(n):
        mn = min(A[i], mn)
 
    # Return the answer
    return mn
 
# Driver Code
 
# Given array arr[]
A = [ 7, 10, 12 ]
 
n = len(A)
 
# Function call
print(maximumModuloValue(A, n))
 
# This code is contributed by Shivam Singh


C#




// C# Program to implement
// the above approach
using System;
class GFG{
 
  // Function to find the maximum value
  // possible of the given expression
  // from all permutations of the array
  static int maximumModuloValue(int []A,
                                int n)
  {
    // Stores the minimum value
    // from the array
    int mn = int.MaxValue;
 
    for (int i = 0; i < n; i++)
    {
      mn = Math.Min(A[i], mn);
    }
 
    // Return the answer
    return mn;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []A = {7, 10, 12};
    int n = A.Length;
    Console.WriteLine(maximumModuloValue(A, n));
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// javascript Program to implement
// the above approach
 
    // Function to find the maximum value
    // possible of the given expression
    // from all permutations of the array
    function maximumModuloValue(A , n) {
        // Stores the minimum value
        // from the array
        var mn = Number.MAX_VALUE;
 
        for (i = 0; i < n; i++) {
            mn = Math.min(A[i], mn);
        }
 
        // Return the answer
        return mn;
    }
 
    // Driver Code
     
        var A = [ 7, 10, 12 ];
        var n = A.length;
        document.write(maximumModuloValue(A, n));
 
// This code contributed by umadevi9616
</script>


Output

7






Time Complexity: O(N)
Auxiliary Space: O(1)

Method 2:

Approach:

We can generate all possible permutations of the array and then calculate the value of the expression for each permutation. Finally, we can return the maximum value among all these values.

  • Import the itertools module to generate all permutations of the array.
  • Define the maximize_modulus function that takes an array arr as input.
  • Initialize max_value to negative infinity as the initial maximum value.
  • Use a for loop to generate all permutations of the array using itertools.permutations.
  • For each permutation, initialize value to the first element of the permutation.
  • Use another for loop to calculate the modulus of value with all other elements in the permutation.
  • Update value to the modulus for each iteration of the loop.
  • If value is greater than the current maximum value max_value, update max_value to value.
  • After all permutations have been evaluated, return max_value.

C++




// Nikunj Sonigara
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum modulus value among all permutations of the array
int maximize_modulus(const vector<int>& arr) {
    // Initialize max_value to the smallest possible integer value
    int max_value = numeric_limits<int>::min();
 
    // Create a copy of the array to generate permutations
    vector<int> perm = arr;
 
    // Generate permutations and calculate modulus for each permutation
    do {
        // Initialize value with the first element of the permutation
        int value = perm[0];
 
        // Calculate modulus for the rest of the elements in the permutation
        for (size_t i = 1; i < perm.size(); ++i) {
            value = value % perm[i];
        }
 
        // Update max_value if the current permutation has a higher modulus
        if (value > max_value) {
            max_value = value;
        }
 
    } while (next_permutation(perm.begin(), perm.end())); // Generate the next permutation
 
    // Return the maximum modulus value found
    return max_value;
}
 
int main() {
    // Test with the given inputs
    vector<int> arr1 = {7, 10, 12};
    vector<int> arr2 = {20, 30};
 
    // Output the results of the function for each test case
    cout << maximize_modulus(arr1) << endl;  // Output: 7
    cout << maximize_modulus(arr2) << endl;  // Output: 20
 
    return 0;
}


Java




import java.util.Arrays;
 
public class NikunjSonigara {
 
    // Function to find the maximum modulus value among all permutations of the array
    static int maximizeModulus(int[] arr) {
        // Initialize max value to the smallest possible integer value
        int maxValue = Integer.MIN_VALUE;
 
        // Generate permutations and calculate modulus for each permutation
        do {
            // Initialize value with the first element of the permutation
            int value = arr[0];
 
            // Calculate modulus for the rest of the elements in the permutation
            for (int i = 1; i < arr.length; ++i) {
                value = value % arr[i];
            }
 
            // Update max value if the current permutation has a higher modulus
            if (value > maxValue) {
                maxValue = value;
            }
 
        } while (nextPermutation(arr)); // Generate the next permutation
 
        // Return the maximum modulus value found
        return maxValue;
    }
 
    // Helper function to generate the next permutation
    static boolean nextPermutation(int[] arr) {
        int i = arr.length - 2;
        while (i >= 0 && arr[i] >= arr[i + 1]) {
            i--;
        }
        if (i < 0) {
            return false; // No more permutations
        }
 
        int j = arr.length - 1;
        while (arr[j] <= arr[i]) {
            j--;
        }
 
        // Swap arr[i] and arr[j]
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
 
        // Reverse the remaining part of the array
        reverse(arr, i + 1, arr.length - 1);
 
        return true;
    }
 
    // Helper function to reverse the elements in a range of the array
    static void reverse(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }
 
    public static void main(String[] args) {
        // Test with the given inputs
        int[] arr1 = {7, 10, 12};
        int[] arr2 = {20, 30};
 
        // Output the results of the function for each test case
        System.out.println(maximizeModulus(arr1)); // Output: 7
        System.out.println(maximizeModulus(arr2)); // Output: 20
    }
}


Python3




import itertools
 
def maximize_modulus(arr):
    max_value = float('-inf')
    for perm in itertools.permutations(arr):
        value = perm[0]
        for i in range(1, len(perm)):
            value = value % perm[i]
        if value > max_value:
            max_value = value
    return max_value
 
# Test with the given inputs
arr1 = [7, 10, 12]
arr2 = [20, 30]
print(maximize_modulus(arr1))  # Output: 7
print(maximize_modulus(arr2))  # Output: 20


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    // Function to find the maximum modulus value among all
    // permutations of the array
    static int MaximizeModulus(List<int> arr)
    {
        // Initialize max_value to the smallest possible
        // integer value
        int maxValue = int.MinValue;
 
        // Generate permutations and calculate modulus for
        // each permutation
        var permutations = GetPermutations(arr);
        foreach(var perm in permutations)
        {
            // Initialize value with the first element of
            // the permutation
            int value = perm[0];
 
            // Calculate modulus for the rest of the
            // elements in the permutation
            for (int i = 1; i < perm.Count; ++i) {
                value = value % perm[i];
            }
 
            // Update maxValue if the current permutation
            // has a higher modulus
            if (value > maxValue) {
                maxValue = value;
            }
        }
 
        // Return the maximum modulus value found
        return maxValue;
    }
 
    // Helper function to generate all permutations of a
    // list
    static List<List<int> > GetPermutations(List<int> list)
    {
        if (list.Count == 1)
            return new List<List<int> >{ new List<int>{
                list[0] } };
 
        return list.SelectMany(x => GetPermutations(list.Where(y => !y.Equals(x)).ToList())
                                   .Select(p => { p.Insert(0, x); return p; }))
                   .ToList();
    }
 
    static void Main()
    {
        // Test with the given inputs
        List<int> arr1 = new List<int>{ 7, 10, 12 };
        List<int> arr2 = new List<int>{ 20, 30 };
 
        // Output the results of the function for each test
        // case
        Console.WriteLine(
            MaximizeModulus(arr1)); // Output: 7
        Console.WriteLine(
            MaximizeModulus(arr2)); // Output: 20
    }
}


Javascript




// Function to find the maximum modulus value
function maximizeModulus(arr) {
  let max_value = Number.NEGATIVE_INFINITY; // Initializing max_value to negative infinity
 
  const permutations = permute(arr); // Generating permutations of the input array
 
  // Loop through each permutation
  for (let perm of permutations) {
    let value = perm[0];
     
    // Calculate modulus for the current permutation
    for (let i = 1; i < perm.length; i++) {
      value = value % perm[i];
    }
     
    // Update max_value if a higher modulus is found
    if (value > max_value) {
      max_value = value;
    }
  }
   
  return max_value; // Return the maximum modulus value found
}
 
// Function to generate permutations of an array
function permute(arr) {
  const permutations = []; // Initialize an array to store permutations
 
  // Recursive function to generate permutations using backtracking
  function generatePermutations(arr, start, end) {
    if (start === end) {
      permutations.push([...arr]); // Push the generated permutation to the array
    } else {
      // Generate permutations using backtracking technique
      for (let i = start; i <= end; i++) {
        [arr[start], arr[i]] = [arr[i], arr[start]];
        generatePermutations(arr, start + 1, end);
        [arr[start], arr[i]] = [arr[i], arr[start]];
      }
    }
  }
 
  generatePermutations(arr, 0, arr.length - 1); // Start generating permutations
  return permutations; // Return the array containing all permutations
}
 
// Test cases
const arr1 = [7, 10, 12];
const arr2 = [20, 30];
 
// Display results
console.log(maximizeModulus(arr1));
console.log(maximizeModulus(arr2));


Output

7
20






The time complexity of this approach is O(n!), where n is the length of the array, because we are generating all possible permutations of the array.

 The space complexity is also O(n!) because we need to store all these permutations.



Last Updated : 23 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads