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

C++Server Side ProgrammingProgramming

Problem statement

Given an array arr[], the task is to find the maximum value of arr[i] % arr[j] for all possible pairs.

If the input array is {5, 2} then we can create the result is −

1. 5 % 2 = 1
2. 2 % 5 = 2

Hence answer is 2 as it is maximum.

Algorithm

1. Run two nested loops and calculate the value of arr[i] % arr[j] for every pair
2. Update the maximum answer according to the value calculated

Example

#include <bits/stdc++.h>
using namespace std;
int computeMaxValue(int *arr, int n){
   int ans = 0;
   for (int i = 0; i < n - 1; ++i) {
      for (int j = i + 1; j < n; ++j) {
         int val = max(arr[i] % arr[j], arr[j] % arr[i]);
         ans = max(ans, val);
      }
   }
   return ans;
}
int main(){
   int arr[] = {2, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Result = " << computeMaxValue(arr, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Result = 2
raja
Published on 10-Feb-2020 09:38:38
Advertisements