Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

Input: arr[] = { 2, 3 } 
Output:
2 % 3 = 2 
3 % 2 = 1

Input: arr[] = { 2, 2, 2, 2 } 
Output:

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

Below is the implementation of the above approach:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return maximum value of
// arr[i] % arr[j]
int computeMaxValue(const int* arr, int n)
{
    int ans = 0;
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Check pair (x, y) as well as
            // (y, x) for maximum value
            int val = max(arr[i] % arr[j], arr[j] % arr[i]);
 
            // Update the answer
            ans = max(ans, val);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << computeMaxValue(arr, n);
    return 0;
}


Java




// Java implementation of the above approach
 
import java.util.*;
class GFG {
 
    // Function to return maximum value of
    // arr[i] % arr[j]
    static 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++) {
 
                // Check pair (x, y) as well as
                // (y, x) for maximum value
                int val = Math.max(arr[i] % arr[j],
                                   arr[j] % arr[i]);
 
                // Update the answer
                ans = Math.max(ans, val);
            }
        }
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 2, 3 };
        int n = arr.length;
        System.out.println(computeMaxValue(arr, n));
    }
}
 
// This code is contributed
// by ihritik


Python3




# Python3  implementation of the above approach
 
# Function to return maximum value of
# arr[i] % arr[j]
 
 
def computeMaxValue(arr, n):
 
    ans = 0
    for i in range(0, n-1):
        for j in range(i+1, n):
 
            # Check pair (x, y) as well as
            # (y, x) for maximum value
            val = max(arr[i] % arr[j], arr[j] % arr[i])
 
            # Update the answer
            ans = max(ans, val)
 
    return ans
 
 
# Driver code
arr = [2, 3]
n = len(arr)
print(computeMaxValue(arr, n))
 
# This code is contributed
# by ihritik


C#




// C# implementation of the above approach
 
using System;
class GFG {
 
    // Function to return maximum value of
    // arr[i] % arr[j]
    static 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++) {
 
                // Check pair (x, y) as well as
                // (y, x) for maximum value
                int val = Math.Max(arr[i] % arr[j],
                                   arr[j] % arr[i]);
 
                // Update the answer
                ans = Math.Max(ans, val);
            }
        }
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 3 };
        int n = arr.Length;
        Console.WriteLine(computeMaxValue(arr, n));
    }
}
 
// This code is contributed
// by ihritik


PHP




<?php
// PHP implementation of the above approach
 
// Function to return maximum value of
// arr[i] % arr[j]
function computeMaxValue($arr, $n)
{
    $ans = 0;
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = $i + 1; $j < $n; $j++) {
 
            // Check pair (x, y) as well as
            // (y, x) for maximum value
            $val = max($arr[$i] % $arr[$j],
                        $arr[$j] % $arr[$i]);
 
            // Update the answer
            $ans = max($ans, $val);
        }
    }
    return $ans;
}
 
// Driver code
$arr = array( 2, 3 );
$n = sizeof($arr);
echo computeMaxValue($arr, $n);
         
// This code is contributed
// by ihritik
 
?>


Javascript




<script>
 
    // Javascript implementation of
    // the above approach
     
    // Function to return maximum value of
    // arr[i] % arr[j]
    function computeMaxValue(arr, n)
    {
        let ans = 0;
        for (let i = 0; i < n - 1; i++) {
            for (let j = i + 1; j < n; j++) {
       
                // Check pair (x, y) as well as
                // (y, x) for maximum value
                let val = Math.max(arr[i] % arr[j],
                            arr[j] % arr[i]);
       
                // Update the answer
                ans = Math.max(ans, val);
            }
        }
        return ans;
    }
     
    let arr = [ 2, 3 ];
    let n = arr.length;
    document.write(computeMaxValue(arr, n));
     
</script>


Output

2

Time Complexity: O(n2), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required.

Better Approach: The maximum value of A % B will be yielded when A < B and A and B are maximum possible. In other words, the result will be the second greatest element from the array except for the case when all the elements of the array are the same (in that case, the result will be 0). 

1.  convert the given array into set

2. convert the set to list

3.   if length (array) == 1 :# (for corner cases )

       print(0) in that case

4 .else sort the array

5 print (second last element)

Below is the implementation of the above approach: 

C++




#include<bits/stdc++.h>
using namespace std;
 
// Function to return maximum value of arr[i] % arr[j]
int computeMaxValue(int arr[], int n)
{
    // Remove duplicates to handle edge cases (x, x, x)
    set<int> s;
    for (int i = 0; i < n; i++) {
        s.insert(arr[i]);
    }
    int m = s.size();
    int uniqueArr[m];
    int i = 0;
    for (auto x : s) {
        uniqueArr[i++] = x;
    }
    n = m;
 
    if (n == 1) {
        return 0;
    } else {
        // A[i] % A[j] is max when A[i] and A[j] are maximum
        sort(uniqueArr, uniqueArr + n);
        return uniqueArr[n - 2];
    }
}
 
int main()
{
    int arr[] = {2, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << computeMaxValue(arr, n) << endl;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
class Main
{
   
// Function to return maximum value of arr[i] % arr[j]
public static int computeMaxValue(int[] arr, int n)
{
   
    // remove duplicates
    // To handle edge cases (x, x, x)
    Set<Integer> set = new HashSet<>();
    for (int num : arr) {
        set.add(num);
    }
    int[] uniqueArr = new int[set.size()];
    int i = 0;
    for (int num : set) {
        uniqueArr[i++] = num;
    }
    n = uniqueArr.length;
 
    if (n == 1) {
        return 0;
    } else {
        // A[i] % A[j] is max when A[i] and A[j] are maximum
        Arrays.sort(uniqueArr);
        return uniqueArr[n - 2];
    }
}
 
public static void main(String[] args) {
    int[] arr = {2, 3};
    int n = arr.length;
 
    System.out.println(computeMaxValue(arr, n));
}
}
 
// This code is contributed by Edula Vinay Kumar Reddy


Python3




# Python3 implementation of the
# above approach
 
# Function to return maximum value
# of arr[i] % arr[j]
# time complexity O(nlogn)
# space complexity O(1)
def computeMaxValue(arr, n) :
      # remove duplicates
    # To handle edges cases (x , x , x)
    arr = set(arr)
    arr = list(arr)
    if len(arr ) == 1 :
      return 0
    else :
      # A[i] % A[j] is max when A[i] and A[j] is maximum
      arr.sort()
      return arr[-2]
 
# Driver code
if __name__ == "__main__" :
    arr = [ 2, 3 ]
    n = len(arr)
     
    print(computeMaxValue(arr, n))
 
# This code is contributed by Shushant Kumar


Javascript




// Function to return maximum value of arr[i] % arr[j]
function computeMaxValue(arr, n)
{
 
    // Remove duplicates to handle edge cases (x, x, x)
    let set = new Set(arr);
    let uniqueArr = Array.from(set);
    n = uniqueArr.length;
 
    if (n == 1) {
        return 0;
    } else {
     
        // A[i] % A[j] is max when A[i] and A[j] are maximum
        uniqueArr.sort((a, b) => a - b);
        return uniqueArr[n - 2];
    }
}
 
let arr = [2, 3];
let n = arr.length;
 
console.log(computeMaxValue(arr, n));


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
    static int computeMaxValue(int[] arr, int n)
    {
        // Remove duplicates to handle edge cases (x, x, x)
        HashSet<int> s = new HashSet<int>(arr);
        int m = s.Count;
        int[] uniqueArr = new int[m];
        int i = 0;
        foreach(int x in s) { uniqueArr[i++] = x; }
        n = m;
        if (n == 1) {
            return 0;
        }
        else {
            // A[i] % A[j] is max when A[i] and A[j] are
            // maximum
            Array.Sort(uniqueArr);
            return uniqueArr[n - 2];
        }
    }
 
    public static void Main()
    {
        int[] arr = new int[] { 2, 3 };
        int n = arr.Length;
 
        Console.WriteLine(computeMaxValue(arr, n));
    }
}


Output

2

Time Complexity: O(nlogn), where n is the size of the given array. as we used sorting.
Auxiliary Space: O(1), no extra space is required.

Efficient Approach: The maximum value of A % B will be yielded when A < B and A and B are maximum possible. In other words, the result will be the second greatest element from the array except for the case when all the elements of the array are the same (in that case, the result will be 0). 

A = second largest element of the array. 
B = largest element of the array and A < B. 
Maximum value of A % B = A.
Corner case: If all the elements of the array are same say arr[] = {x, x, x, x} then the result will be x % x = 0
 

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return maximum value of
// arr[i] % arr[j]
int computeMaxValue(const int* arr, int n)
{
    bool allSame = true;
    int i = 1;
    while (i < n) {
 
        // If current element is different
        // from the previous element
        if (arr[i] != arr[i - 1]) {
            allSame = false;
            break;
        }
        i++;
    }
 
    // If all the elements of the array are equal
    if (allSame)
        return 0;
 
    // Maximum element from the array
    int max = *std::max_element(arr, arr + n);
    int secondMax = 0;
    for (i = 0; i < n; i++) {
        if (arr[i] < max && arr[i] > secondMax)
            secondMax = arr[i];
    }
 
    // Return the second maximum element
    // from the array
    return secondMax;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << computeMaxValue(arr, n);
    return 0;
}


Java




// Java implementation of the above approach
class GFG {
 
    // Function to return maximum value of
    // arr[i] % arr[j]
    static int computeMaxValue(int arr[], int n)
    {
        boolean allSame = true;
        int i = 1;
        while (i < n) {
 
            // If current element is different
            // from the previous element
            if (arr[i] != arr[i - 1]) {
                allSame = false;
                break;
            }
            i++;
        }
 
        // If all the elements of the
        // array are equal
        if (allSame)
            return 0;
 
        // Maximum element from the array
        int max = -1;
        for (i = 0; i < n; i++) {
            if (max < arr[i])
                max = arr[i];
        }
        int secondMax = 0;
        for (i = 0; i < n; i++) {
            if (arr[i] < max && arr[i] > secondMax)
                secondMax = arr[i];
        }
 
        // Return the second maximum element
        // from the array
        return secondMax;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 2, 3 };
        int n = arr.length;
        System.out.println(computeMaxValue(arr, n));
    }
}
 
// This code is contributed
// by 29AjayKumar


Python3




# Python3 implementation of the
# above approach
 
# Function to return maximum value
# of arr[i] % arr[j]
 
 
def computeMaxValue(arr, n):
 
    allSame = True
    i = 1
    while (i < n):
 
        # If current element is different
        # from the previous element
        if (arr[i] != arr[i - 1]):
            allSame = False
            break
 
        i += 1
 
    # If all the elements of the
    # array are equal
    if (allSame):
        return 0
 
    # Maximum element from the array
    max_element = max(arr)
 
    secondMax = 0
    for i in range(n):
        if (arr[i] < max_element and
                arr[i] > secondMax):
            secondMax = arr[i]
 
    # Return the second maximum element
    # from the array
    return secondMax
 
 
# Driver code
if __name__ == "__main__":
    arr = [2, 3]
    n = len(arr)
 
    print(computeMaxValue(arr, n))
 
# This code is contributed by Ryuga


C#




// C# implementation of the above approach
using System;
 
class GFG {
 
    // Function to return maximum value of
    // arr[i] % arr[j]
    static int computeMaxValue(int[] arr, int n)
    {
        bool allSame = true;
        int i = 1;
        while (i < n) {
 
            // If current element is different
            // from the previous element
            if (arr[i] != arr[i - 1]) {
                allSame = false;
                break;
            }
            i++;
        }
 
        // If all the elements of the
        // array are equal
        if (allSame)
            return 0;
 
        // Maximum element from the array
        int max = -1;
        for (i = 0; i < n; i++) {
            if (max < arr[i])
                max = arr[i];
        }
        int secondMax = 0;
        for (i = 0; i < n; i++) {
            if (arr[i] < max && arr[i] > secondMax)
                secondMax = arr[i];
        }
 
        // Return the second maximum element
        // from the array
        return secondMax;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 3 };
        int n = arr.Length;
        Console.Write(computeMaxValue(arr, n));
    }
}
 
// This code is contributed by Ita_c.


PHP




<?php
// PHP implementation of the above approach
 
// Function to return maximum value of
// arr[i] % arr[j]
function computeMaxValue($arr, $n)
{
    $allSame = true;
    $i = 1;
    while ($i < $n)
    {
 
        // If current element is different
        // from the previous element
        if ($arr[$i] != $arr[$i - 1])
        {
            $allSame = false;
            break;
        }
        $i++;
    }
 
    // If all the elements of the
    // array are equal
    if ($allSame)
        return 0;
 
    // Maximum element from the array
    $max = max($arr);
    $secondMax = 0;
    for ($i = 0; $i < $n; $i++)
    {
        if ($arr[$i] < $max &&
            $arr[$i] > $secondMax)
            $secondMax = $arr[$i];
    }
 
    // Return the second maximum
    // element from the array
    return $secondMax;
}
 
// Driver code
$arr = array(2, 3);
$n = sizeof($arr);
echo computeMaxValue($arr, $n);
 
// This code is contributed by ajit.
?>


Javascript




<script>   
    // Javascript implementation of the above approach
     
    // Function to return maximum value of
    // arr[i] % arr[j]
    function computeMaxValue(arr, n)
    {
        let allSame = true;
        let i = 1;
        while (i < n)
        {
 
            // If current element is different
            // from the previous element
            if (arr[i] != arr[i - 1])
            {
                allSame = false;
                break;
            }
            i++;
        }
 
        // If all the elements of the
        // array are equal
        if (allSame)
            return 0;
 
        // Maximum element from the array
        let max = -1;
        for(i = 0; i < n; i++)
        {
            if(max < arr[i])
                max = arr[i];
        }
        let secondMax = 0;
        for (i = 0; i < n; i++)
        {
            if (arr[i] < max && arr[i] > secondMax)
                secondMax = arr[i];
        }
 
        // Return the second maximum element
        // from the array
        return secondMax;
    }
     
    let arr = [ 2, 3 ];
    let n = arr.length;
    document.write(computeMaxValue(arr, n));
 
</script>


Output

2

Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required.



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