Maximum value of arr[i] % arr[j] for a given array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n elements. Our task is to create a program that will find the maximum value of arr[i]%arr[j] for a given array.

So, basically we need to find the value of the maximum remainder while dividing two elements of the array.

Let’s take an example to understand the problem,

Input − array{3, 6, 9, 2, 1}

Output − 6

Explanation

3%3 = 0; 3%6 = 3; 3%9 = 3; 3%2 = 1; 3%1 = 0
6%3 = 0; 6%6 = 0; 6%9 = 6; 6%2 = 0; 6%1 =0
9%3 = 0; 9%6 = 3; 9%9 = 0 9%2 = 1; 9%1 = 0
2%3 = 2; 2%6 = 2; 2%9 = 2; 2%2 = 0; 2%1 = 0
1%3 = 1; 1%6 = 1; 1%9 = 1; 1%2 =1; 1%1 = 0
Out the above remainders the maximum is 6.

So, a direct approach to find the solution will be to calculate the remainder for each and every pair and then find the maximum of all of them. But this approach will not be effective as it’s time complexity will be of the order n2.

So, an effective solution will be using the logic that the value of x%y will be maximum when y>x then the remainder will be x. And out of all elements of the array if we take two maximum elements, then the result will be maximum. For this, we will sort the array and then iterate the last and second last element to provide the result.

Example

Program to illustrate the implementation of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxRemainder(int arr[], int n){
   bool hasSameValues = true;
   for(int i = 1; i<n; i++) {
      if (arr[i] != arr[i - 1]) {
         hasSameValues = false;
         break;
      }
   }
   if (hasSameValues)
      return 0;
   sort(arr, arr+n);
      return arr[n-2];
}
int main(){
   int arr[] = { 3, 6, 9, 2, 1 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum remainder on dividing two elements of the array is "<<maxRemainder(arr, n);
   return 0;
}

Output

The maximum remainder on dividing two elements of the array is 6
raja
Published on 10-Feb-2020 14:08:38
Advertisements