Maximum modulo of all the pairs of array where arr[i] >= arr[j] in C++


In this problem, we are given an array, are of n elements. Our task is to create a program to find the maximum modulo of all pairs of array where arr[i] >= arr[j].

Here, we have to find the maximum value of arr[i] % arr[j] where arr[i] >= arr[j].

Let’s take an example to understand the problem,

Input − arr[] = {3, 5, 9}

Output − 4

Explanation

All possible Pairs arr[i] and arr[j],
5, 3 => 5%3 = 2
9, 3 => 9%3 = 0
9, 5 => 9%5 = 4

To solve this problem, a simple and direct approach will be run two nested loops and find the modulo for every possible pair. Then, find the maximum of them. But, this solution will not be efficient as its complexity will be of order O(n^2).

An effective approach will be applied on sorted array. The algorithm will we applied in the following manner −

For every element arr[j] in the array, we will find values which are multiples of arr[j] say x till we find value greater than the largest element of the array. Then, we will find all value of an array such that arr[i] < x. Find arr[i] % arr[j], and store the maximum of modulo value in the maxModulo variable after each operation.

Let’s solve an example using this solution which will show the functioning of the algorithm −

arr = {3, 5, 9}
arr[j] = 3 for j = 0,
x = {6, 9}
For x = 6, arr[i] = 5,
arr[i]%arr[j] = 6%5 = 2, maxModulo = 2
For x = 9, arr[i] = 9,
arr[i]%arr[j] = 9%3 = 0, maxModulo = 2
arr[j] = 5 for j = 1,
x = {10}
For x = 10, arr[i] = 9,
arr[i]%arr[j] = 9%5 = 4, maxModulo =4

Example

Program to find the maximum modulo of all pairs of array where arr[i] >= arr[j] −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxModulo(int arr[], int n) {
   int maxModulo = 0;
   sort(arr, arr + n);
   for (int j = n - 2; j >= 0; --j) {
      if (maxModulo >= arr[j])
         break;
      if (arr[j] == arr[j + 1])
         continue;
      for (int k = 2 * arr[j]; k <= arr[n - 1] + arr[j]; k += arr[j]) {
         int i = lower_bound(arr, arr + n, k) - arr;
         maxModulo = max(maxModulo, arr[i - 1] % arr[j]);
      }
   }
   return maxModulo;
}
int main() {
   int arr[] = {3, 5, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum modulo of all pairs is "<<maxModulo(arr, n);
}

Output

The maximum modulo of all pairs is 4

Updated on: 03-Jun-2020

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements