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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read