Open In App

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

Last Updated : 29 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of n integers. Find the maximum value of arr[i] mod arr[j] where arr[i] >= arr[j] and 1 <= i, j <= n 

Examples: 

Input: arr[] = {3, 4, 7}
Output: 3
Explanation: There are 3 pairs which satisfiy arr[i] >= arr[j] are:- {4, 3} , {7, 3} and {7, 4}. For which the Maximum modulo value among all is 3 ( 7%4 =3).

Input: arr[] = {3, 7, 4, 11}
Output: 4
Explanation: There are 6 pairs which satisfiy arr[i] >= arr[j] are:- {4, 3} , {7, 3}, {11, 3}, {7, 4}, {11, 4}, {11, 7} . For which the Maximum modulo value among all is 4 (11%7 = 4).

Input: arr[] = {4, 4, 4}
Output: 0
Explanation: Since all the values of the array are equal, the Maximum modulo value is 0.

[Naive Approach] – Using Nested Loops – O(n2) Time and O(1) Space

The idea for this approach is to run two nested for loops and select the maximum of every possible pairs after taking modulo of them. Time complexity of this approach will be O(n2) which will not be sufficient for large value of n.

C++
#include <bits/stdc++.h>
using namespace std;

int maxModValue(vector<int>& arr) {
    int n = arr.size();
    int ans = 0;
    
    // Two nested loops to check every pair (i, j)
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[i] >= arr[j]) {  // Only calculate mod if arr[i] >= arr[j]
                int currMod = arr[i] % arr[j];
                ans = max(ans, currMod);
            }
        }
    }
    
    return ans;
}

int main() {
    vector<int> arr = { 3, 4, 5, 9, 11 };
    cout << maxModValue(arr) << endl;
    return 0;
}
Java
public class GfG {
    public static int maxModValue(int[] arr) {
        int n = arr.length;
        int ans = 0;
        
        // Two nested loops to check every pair (i, j)
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[i] >= arr[j]) {  // Only calculate mod if arr[i] >= arr[j]
                    int currMod = arr[i] % arr[j];
                    ans = Math.max(ans, currMod);
                }
            }
        }
        
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = { 3, 4, 5, 9, 11 };
        System.out.println(maxModValue(arr));
    }
}
Python
def maxModValue(arr):
    n = len(arr)
    ans = 0
    
    # Two nested loops to check every pair (i, j)
    for i in range(n):
        for j in range(n):
            if arr[i] >= arr[j]:  # Only calculate mod if arr[i] >= arr[j]
                currMod = arr[i] % arr[j]
                ans = max(ans, currMod)
    
    return ans

if __name__ == '__main__':
    arr = [3, 4, 5, 9, 11]
    print(maxModValue(arr))
C#
using System;
using System.Linq;

public class GfG {
    public static int maxModValue(int[] arr) {
        int n = arr.Length;
        int ans = 0;
        
        // Two nested loops to check every pair (i, j)
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[i] >= arr[j]) {  // Only calculate mod if arr[i] >= arr[j]
                    int currMod = arr[i] % arr[j];
                    ans = Math.Max(ans, currMod);
                }
            }
        }
        
        return ans;
    }

    public static void Main() {
        int[] arr = { 3, 4, 5, 9, 11 };
        Console.WriteLine(maxModValue(arr));
    }
}
JavaScript
function maxModValue(arr) {
    let n = arr.length;
    let ans = 0;
    
    // Two nested loops to check every pair (i, j)
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (arr[i] >= arr[j]) {  // Only calculate mod if arr[i] >= arr[j]
                let currMod = arr[i] % arr[j];
                ans = Math.max(ans, currMod);
            }
        }
    }
    
    return ans;
}

const arr = [3, 4, 5, 9, 11];
console.log(maxModValue(arr));

Output
4

[Expected Approach for Small Range] – Using Sorting and Binary Search – O(nlog(n) + Mlog(M)) Time and O(1) Space

The idea for this approach is to sort the array and then use binary search. For each arr[j], iterate through multiples of arr[j] in the range from 2 * arr[j] to M + arr[j] (where M is the maximum value in the sequence). For each multiple x, use binary search to find the largest arr[i] such that arr[i] < x. This ensures we choose values of arr[i] that maximize arr[i] % arr[j]. Repeat the process for each arr[j] and update the result accordingly.

Example:

If arr[] = {4, 6, 7, 8, 10, 12, 15} then for
first element, i.e., arr[j] = 4 we iterate
through x = {8, 12, 16}.
Therefore for each value of x, a[i] will be:-
x = 8, arr[i] = 7 (7 < 8)
ans = 7 mod 4 = 3
x = 12, arr[i] = 10 (10 < 12)
ans = 10 mod 4 = 2 (Since 2 < 3, No update)
x = 16, arr[i] = 15 (15 < 16)
ans = 15 mod 4 = 3 (Since 3 == 3, No need to update)

C++
#include <bits/stdc++.h>
using namespace std;

int maxModValue(vector<int>& arr)
{
    int ans = 0;
    int n = arr.size();
    
    // Sort the vector by using inbuilt sort function
    sort(arr.begin(), arr.end());

    for (int j = n - 2; j >= 0; --j) {
        
        // Break loop if answer is greater or equals to
        // the arr[j] as any number modulo with arr[j]
        // can only give maximum value up-to arr[j]-1
        if (ans >= arr[j])
            break;

        // If both elements are same then skip the next
        // loop as it would be worthless to repeat the
        // rest process for same value
        if (arr[j] == arr[j + 1])
            continue;

        for (int i = 2 * arr[j]; i <= arr[n - 1] + arr[j]; i += arr[j]) {
            
            // Fetch the index which is greater than or
            // equals to arr[i] by using binary search
            // inbuilt lower_bound() function of C++
            int ind = lower_bound(arr.begin(), arr.end(), i) - arr.begin();

            // Update the answer
            ans = max(ans, arr[ind - 1] % arr[j]);
        }
    }
    return ans;
}

// Driver code
int main()
{
    vector<int> arr = { 3, 4, 5, 9, 11 };
    cout << maxModValue(arr);
}
Java
// Java program to find Maximum modulo value

import java.util.Arrays;

class Test {
    static int maxModValue(int arr[])
    {
        int ans = 0;
        int n = arr.length;

        // Sort the array[] by using inbuilt sort function
        Arrays.sort(arr);

        for (int j = n - 2; j >= 0; --j) {
            
            // Break loop if answer is greater or equals to
            // the arr[j] as any number modulo with arr[j]
            // can only give maximum value up-to arr[j]-1
            if (ans >= arr[j])
                break;

            // If both elements are same then skip the next
            // loop as it would be worthless to repeat the
            // rest process for same value
            if (arr[j] == arr[j + 1])
                continue;

            for (int i = 2 * arr[j]; i <= arr[n - 1] + arr[j]; i += arr[j]) {
                
                // Fetch the index which is greater than or
                // equals to arr[i] by using binary search
                int ind = Arrays.binarySearch(arr, i);

                if (ind < 0)
                    ind = Math.abs(ind + 1);

                else {
                    while (arr[ind] == i) {
                        ind--;

                        if (ind == 0) {
                            ind = -1;
                            break;
                        }
                    }
                    ind++;
                }

                // Update the answer
                ans = Math.max(ans, arr[ind - 1] % arr[j]);
            }
        }
        return ans;
    }

    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 3, 4, 5, 9, 11 };
        System.out.println(maxModValue(arr));
    }
}
Python
from bisect import bisect_left

def max_mod_value(arr):
    res = 0
    n = len(arr)

    # Sort the array
    arr.sort()

    for j in range(n - 2, -1, -1):
        
        # Break loop if result is greater or equal to arr[j]
        if res >= arr[j]:
            break

        # Skip duplicate values to avoid redundant calculations
        if arr[j] == arr[j + 1]:
            continue

        for i in range(2 * arr[j], arr[-1] + arr[j] + 1, arr[j]):
            
            # Find the index of the first element >= i using binary search
            ind = bisect_left(arr, i)

            # Update the result with the max modulo value
            res = max(res, arr[ind - 1] % arr[j])

    return res

# Example usage
arr = [3, 4, 5, 9, 11]
print(max_mod_value(arr))  # Output: 4
C#
// C# program to find Maximum modulo value
using System;

public class GFG {
    static int maxModValue(int[] arr)
    {
        int n = arr.Length;
        int ans = 0;

        // Sort the array[] by using inbuilt
        // sort function
        Array.Sort(arr);

        for (int j = n - 2; j >= 0; --j)
        {
            // Break loop if answer is greater
            // or equals to the arr[j] as any
            // number modulo with arr[j] can 
            // only give maximum value up-to
            // arr[j]-1
            if (ans >= arr[j])
                break;

            // If both elements are same then
            // skip the next loop as it would
            // be worthless to repeat the
            // rest process for same value
            if (arr[j] == arr[j + 1])
                continue;

            for (int i = 2 * arr[j]; 
                      i <= arr[n - 1] + arr[j];
                                   i += arr[j])
            {
                // Fetch the index which is 
                // greater than or equals to
                // arr[i] by using binary search

                int ind = Array.BinarySearch(arr, i);

                if (ind < 0)
                    ind = Math.Abs(ind + 1);

                else {
                    while (arr[ind] == i) {
                        ind--;

                        if (ind == 0) {
                            ind = -1;
                            break;
                        }
                    }
                    ind++;
                }

                // Update the answer
                ans = Math.Max(ans, arr[ind - 1]
                                       % arr[j]);
            }
        }
        return ans;
    }

    // Driver method
    public static void Main()
    {
        int[] arr = { 3, 4, 5, 9, 11 };
        Console.WriteLine(
                 maxModValue(arr));
    }
}

// This code is contributed by Sam007.
JavaScript
function maxModValue(arr) {
    let res = 0, n = arr.length;

    // Sort the array
    arr.sort((a, b) => a - b);

    for (let j = n - 2; j >= 0; --j) {
        
        // Break loop if result is greater or equal to arr[j]
        if (res >= arr[j]) break;

        // Skip duplicate values to avoid redundant calculations
        if (arr[j] === arr[j + 1]) continue;

        for (let i = 2 * arr[j]; i <= arr[n - 1] + arr[j]; i += arr[j]) {
            
            // Find the index of the first element >= i using binary search
            let ind = lowerBound(arr, i);

            // Update the result with the max modulo value
            res = Math.max(res, arr[ind - 1] % arr[j]);
        }
    }
    return res;
}

// Binary search function to find lower bound (first index where arr[idx] >= x)
function lowerBound(arr, x) {
    let lo = 0, hi = arr.length;
    while (lo < hi) {
        let mid = Math.floor((lo + hi) / 2);
        if (arr[mid] < x) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

// Example usage
console.log(maxModValue([3, 4, 5, 9, 11]));  // Output: 4

Output
4

ime complexity: O(nlog(n) + Mlog(M)) where n is total number of elements and M is maximum value of all the elements. 
Auxiliary space: O(1)



Next Article

Similar Reads