Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array
Last Updated :
23 Dec, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int min( int a, int b)
{
return (a > b) ? b : a;
}
int maximumModuloValue( int A[], int n)
{
int mn = INT_MAX;
for ( int i = 0; i < n; i++) {
mn = min(A[i], mn);
}
return mn;
}
int main()
{
int A[] = { 7, 10, 12 };
int n = ( sizeof (A) / ( sizeof (A[0])));
cout << maximumModuloValue(A, n)
<< endl;
return 0;
}
|
Java
import java.io.*;
class GFG{
static int maximumModuloValue( int A[], int n)
{
int mn = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
{
mn = Math.min(A[i], mn);
}
return mn;
}
public static void main(String[] args)
{
int A[] = { 7 , 10 , 12 };
int n = A.length;
System.out.println(maximumModuloValue(A, n));
}
}
|
Python3
import sys
def maximumModuloValue(A, n):
mn = sys.maxsize
for i in range (n):
mn = min (A[i], mn)
return mn
A = [ 7 , 10 , 12 ]
n = len (A)
print (maximumModuloValue(A, n))
|
C#
using System;
class GFG{
static int maximumModuloValue( int []A,
int n)
{
int mn = int .MaxValue;
for ( int i = 0; i < n; i++)
{
mn = Math.Min(A[i], mn);
}
return mn;
}
public static void Main(String[] args)
{
int []A = {7, 10, 12};
int n = A.Length;
Console.WriteLine(maximumModuloValue(A, n));
}
}
|
Javascript
<script>
function maximumModuloValue(A , n) {
var mn = Number.MAX_VALUE;
for (i = 0; i < n; i++) {
mn = Math.min(A[i], mn);
}
return mn;
}
var A = [ 7, 10, 12 ];
var n = A.length;
document.write(maximumModuloValue(A, n));
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int maximize_modulus( const vector< int >& arr) {
int max_value = numeric_limits< int >::min();
vector< int > perm = arr;
do {
int value = perm[0];
for ( size_t i = 1; i < perm.size(); ++i) {
value = value % perm[i];
}
if (value > max_value) {
max_value = value;
}
} while (next_permutation(perm.begin(), perm.end()));
return max_value;
}
int main() {
vector< int > arr1 = {7, 10, 12};
vector< int > arr2 = {20, 30};
cout << maximize_modulus(arr1) << endl;
cout << maximize_modulus(arr2) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class NikunjSonigara {
static int maximizeModulus( int [] arr) {
int maxValue = Integer.MIN_VALUE;
do {
int value = arr[ 0 ];
for ( int i = 1 ; i < arr.length; ++i) {
value = value % arr[i];
}
if (value > maxValue) {
maxValue = value;
}
} while (nextPermutation(arr));
return maxValue;
}
static boolean nextPermutation( int [] arr) {
int i = arr.length - 2 ;
while (i >= 0 && arr[i] >= arr[i + 1 ]) {
i--;
}
if (i < 0 ) {
return false ;
}
int j = arr.length - 1 ;
while (arr[j] <= arr[i]) {
j--;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
reverse(arr, i + 1 , arr.length - 1 );
return true ;
}
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) {
int [] arr1 = { 7 , 10 , 12 };
int [] arr2 = { 20 , 30 };
System.out.println(maximizeModulus(arr1));
System.out.println(maximizeModulus(arr2));
}
}
|
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
arr1 = [ 7 , 10 , 12 ]
arr2 = [ 20 , 30 ]
print (maximize_modulus(arr1))
print (maximize_modulus(arr2))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static int MaximizeModulus(List< int > arr)
{
int maxValue = int .MinValue;
var permutations = GetPermutations(arr);
foreach ( var perm in permutations)
{
int value = perm[0];
for ( int i = 1; i < perm.Count; ++i) {
value = value % perm[i];
}
if (value > maxValue) {
maxValue = value;
}
}
return maxValue;
}
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()
{
List< int > arr1 = new List< int >{ 7, 10, 12 };
List< int > arr2 = new List< int >{ 20, 30 };
Console.WriteLine(
MaximizeModulus(arr1));
Console.WriteLine(
MaximizeModulus(arr2));
}
}
|
Javascript
function maximizeModulus(arr) {
let max_value = Number.NEGATIVE_INFINITY;
const permutations = permute(arr);
for (let perm of permutations) {
let value = perm[0];
for (let i = 1; i < perm.length; i++) {
value = value % perm[i];
}
if (value > max_value) {
max_value = value;
}
}
return max_value;
}
function permute(arr) {
const permutations = [];
function generatePermutations(arr, start, end) {
if (start === end) {
permutations.push([...arr]);
} else {
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);
return permutations;
}
const arr1 = [7, 10, 12];
const arr2 = [20, 30];
console.log(maximizeModulus(arr1));
console.log(maximizeModulus(arr2));
|
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.
Similar Reads
Replacing adjacent opposite sign pairs with their absolute max in an array
Given an array arr[] of size n, the task is to find the final array by repeatedly performing the following operations if two elements of opposite signs are adjacent: Remove both opposite signed elements from the maximumarray and insert the element having maximum absolute value along with its sign.If
7 min read
Maximize minimum distance between repetitions from any permutation of the given Array
Given an array arr[], consisting of N positive integers in the range [1, N], the task is to find the largest minimum distance between any consecutive repetition of an element from any permutation of the given array. Examples: Input: arr[] = {1, 2, 1, 3} Output: 3 Explanation: The maximum possible di
5 min read
Minimize modulo operations to make given Array a permutation of [1, N]
Given an array arr[] of size N, the task is to find the minimum number of operations required to make the array a permutation of numbers in range [1, N] where, in each operation, an element at any index i can be replaced by arr[i]%k (k = any value greater than 0). Return -1 if the array cannot be ma
7 min read
Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array
Given an array arr[] consisting of N integers, the task is to find the maximum value of Bitwise AND of the first element with the complement of remaining elements for any permutation of this array, i.e. A1 &(~A2) & (~A3) & ......& (~An) Examples: Input: arr[] = {1, 2, 4, 8, 16} Outpu
8 min read
Maximize array sum by replacing equal adjacent pairs by their sum and X respectively
Given two integers N and X which denotes the size of an array arr[] and the initial value of all the array elements respectively, the task is to find the maximum sum possible from the given array after performing the following operation any number of times. Choose any valid index i for which arr[i]
6 min read
Minimize cost to make given Array a permutation of 1 to N by given replacements
Given two arrays a[] and b[] of length N and an integer K (1 ⤠K ⤠N). All the integers in array a[] lie within the range [1, K]. ith value in array b[] denotes the cost of replacing a[i] with any number in the range [1, N]. The task is to find the minimum cost to replace the elements of array a[] t
6 min read
Smallest array that can be obtained by replacing adjacent pairs with their products
Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations: Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.If all array el
4 min read
Minimum operations to convert an Array into a Permutation of 1 to N by replacing with remainder from some d
Given an array arr[] of size N, the task is to find the minimum number of operations to convert the array into a permutation of [1, n], in each operation, an element a[i] can be replaced by a[i] % d where d can be different in each operation performed. If it is not possible print -1. Examples: Input
8 min read
Maximize Array sum by replacing any K elements by its modulo with any positive integer
Given an array of positive integer arr[], and a number K. the task is to maximize the sum of the array by replacing any K elements of the array by taking modulus with any positive integer which is less than arr[i] i.e, (arr[i] = arr[i]%X where X ⤠arr[i]). Examples: Input: arr[] = {5, 7, 18, 12, 11,
5 min read
Count of permutations with minimum possible maximum XOR of adjacent pairs
Given an integer N, consider an array having elements in the range [0, N-1] such that the maximum Bitwise XOR of all adjacent pairs is minimum out of all possible permutations of the array. Find the number of such permutations. Examples: Input: N = 3Output: 2Explanation: A[] = {2, 0, 1}, Maximum of
8 min read