Maximum modulo of all the pairs of array where arr[i]>=arr[j]
Last Updated :
29 Mar, 2025
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));
[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
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)
Similar Reads
Maximum value of arr[i] + arr[j] + i â j for any pair of an array Given an array arr[] consisting of N integers, the task is to find the maximum value of (arr[i] + arr[j] + i ? j) for any possible pair (i, j) of the given array. Examples: Input: arr[] = {1, 9, 3, 6, 5}Output: 13Explanation:The pair of the array having the maximum value of (arr[i] + arr[j] + i ? j)
9 min read
Maximum sum of minimums of pairs in an array Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1,
4 min read
Maximum AND value of a pair in an array Given an array of N positive elements, the task is to find the maximum AND value generated by any pair of elements from the array. Examples: Input: arr1[] = {16, 12, 8, 4}Output: 8Explanation: 8 AND12 will give us the maximum value 8 Input: arr1[] = {4, 8, 16, 2}Output: 0 Recommended PracticeMaximum
12 min read
Maximum value of arr[i] % arr[j] for a given array 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 2 % 3 = 2 3 % 2 = 1 Input: arr[] = { 2, 2, 2, 2 } Output: 0 Naive Approach: Run two nested loops and calculate the value of arr[i] % arr[j] for every pair
13 min read
Maximum j - i in an array such that arr[i] <= arr[j] Given an array arr[] of n positive integers, the task is to find the maximum of j - i subjected to the constraint of arr[i] <= arr[j] and i <= j.Examples : Input: arr[] = [34, 8, 10, 3, 2, 80, 30, 33, 1]Output: 6 Explanation: for i = 1 and j = 7.Input: arr[] = [1, 2, 3, 4, 5, 6]Output: 5 Expla
15+ min read
Find the maximum possible value of a[i] % a[j] over all pairs of i and j Given an array arr[] of N positive integers. The task is to find the maximum possible value of a[i] % a[j] over all pairs of i and j. Examples: Input: arr[] = {4, 5, 1, 8} Output: 5 If we choose the pair (5, 8), then 5 % 8 gives us 5 which is the maximum possible. Input: arr[] = {7, 7, 8, 8, 1} Outp
6 min read
Maximize value of (arr[i] - i) - (arr[j] - j) in an array Given an array, arr[] find the maximum value of (arr[i] - i) - (arr[j] - j) where i is not equal to j. Where i and j vary from 0 to n-1 and n is size of input array arr[]. Examples: Input : arr[] = {9, 15, 4, 12, 13} Output : 12 We get the maximum value for i = 1 and j = 2 (15 - 1) - (4 - 2) = 12 In
10 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN) Let (a, b) represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Ou
13 min read
Maximum value of (arr[i] * arr[j]) + (arr[j] - arr[i])) possible for any pair in an array Given an array arr[] consisting of N integers, the task is to find the maximum possible value of the expression (arr[i] * arr[j]) + (arr[j] - arr[i])) for any pair (i, j), such that i ? j and 0 ? (i, j) < N. Examples: Input: arr[] = {-2, -8, 0, 1, 2, 3, 4}Output: 22Explanation:For the pair (-8, -
6 min read
Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[] Given an array of n distinct elements. Find the maximum of product of Minimum of two numbers in the array and absolute difference of their positions, i.e., find maximum value of abs(i - j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Examples : Input : arr[] = {3, 2, 1, 4} Output: 9 // ar
6 min read