# Maximize remainder of sum of a pair of array elements with different parity modulo K

Given an array arr[] of size N, consisting of N / 2 even and odd integers each, and an integer K, the task is to find the maximum remainder of sum of a pair of array elements of different parity modulo K.

Examples:

Input: arr[] = {3, 2, 4, 11, 6, 7}, K = 7
Output: 6
Explanation:
Sum of a pair of array elements = 2 + 11
Sum % K = 13 % 7 = 6.
Therefore, the maximum remainder possible is 6.

Input: arr[] = {8, 11, 17, 16}, K = 13
Output: 12

Approach: Follow the steps below to solve the problem:

• Initialize a HashSet, say even, to store all even array elements.
• Initialize a TreeSet, say odd, to store all odd array elements.
• Initialize a variable, say max_rem, to store the maximum remainder possible.
• Traverse the HashSet and for each element, find its complement and search for it in the set odd, which is less than equal to its complement.
• Update max_rem with the sum of elements, and it’s complement.
• Print the maximum remainder i.e. value of max_rem.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to find the maximum` `// remainder of sum of a pair` `// of array elements modulo K` `void` `maxRemainder(``int` `A[], ``int` `N, ``int` `K)` `{` `    `  `    ``// Stores all even numbers` `    ``unordered_set<``int``> even;`   `    ``// Stores all odd numbers` `    ``set<``int``> odd;`   `    ``// Segregate remainders of even` `    ``// and odd numbers in respective sets` `    ``for``(``int` `i = 0; i < N; i++) ` `    ``{` `        ``int` `num = A[i];` `        `  `        ``if` `(num % 2 == 0)` `            ``even.insert(num % K);` `        ``else` `            ``odd.insert(num % K);` `    ``}`   `    ``// Stores the maximum` `    ``// remainder obtained` `    ``int` `max_rem = 0;`   `    ``// Find the complement of remainder` `    ``// of each even number in odd set` `    ``for``(``int` `x : even)` `    ``{` `        `  `        ``// Find the complement` `        ``// of remainder x` `        ``int` `y = K - 1 - x;`   `        ``auto` `it = odd.upper_bound(y);` `        ``if` `(it != odd.begin()) ` `        ``{` `            ``it--;` `            ``max_rem = max(max_rem, x + *it);` `        ``}` `    ``}`   `    ``// Print the answer` `    ``cout << max_rem;` `}`   `// Driver code` `int` `main()` `{` `    `  `    ``// Given array` `    ``int` `arr[] = { 3, 2, 4, 11, 6, 7 };`   `    ``// Size of the array` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Given value of K` `    ``int` `K = 7;`   `    ``maxRemainder(arr, N, K);`   `    ``return` `0;` `}`   `// This code is contributed by Kingash`

## Java

 `// Java program for the above approach`   `import` `java.util.*;`   `class` `GFG {`   `    ``// Function to find the maximum` `    ``// remainder of sum of a pair` `    ``// of array elements modulo K` `    ``static` `void` `maxRemainder(``int` `A[],` `                             ``int` `N, ``int` `K)` `    ``{` `        ``// Stores all even numbers` `        ``HashSet even ` `          ``= ``new` `HashSet<>();`   `        ``// Stores all odd numbers` `        ``TreeSet odd ` `          ``= ``new` `TreeSet<>();`   `        ``// Segregate remainders of even` `        ``// and odd numbers in respective sets` `        ``for` `(``int` `num : A) {` `            ``if` `(num % ``2` `== ``0``)` `                ``even.add(num % K);` `            ``else` `                ``odd.add(num % K);` `        ``}`   `        ``// Stores the maximum` `        ``// remainder obtained` `        ``int` `max_rem = ``0``;`   `        ``// Find the complement of remainder` `        ``// of each even number in odd set` `        ``for` `(``int` `x : even) {`   `            ``// Find the complement` `            ``// of remainder x` `            ``int` `y = K - ``1` `- x;` `            ``if` `(odd.floor(y) != ``null``)` `                ``max_rem` `                    ``= Math.max(` `              ``max_rem,` `              ``x + odd.floor(y));` `        ``}`   `        ``// Print the answer` `        ``System.out.print(max_rem);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``// Given array` `        ``int` `arr[] = { ``3``, ``2``, ``4``, ``11``, ``6``, ``7` `};`   `        ``// Size of the array` `        ``int` `N = arr.length;`   `        ``// Given value of K` `        ``int` `K = ``7``;`   `        ``maxRemainder(arr, N, K);` `    ``}` `}`

## Python3

 `# Python3 program for the above approach` `from` `bisect ``import` `bisect_left`   `# Function to find the maximum` `# remainder of sum of a pair` `# of array elements modulo K` `def` `maxRemainder(A, N, K):` `    `  `    ``# Stores all even numbers` `    ``even ``=` `{}`   `    ``# Stores all odd numbers` `    ``odd ``=` `{}`   `    ``# Segregate remainders of even` `    ``# and odd numbers in respective sets` `    ``for` `i ``in` `range``(N):` `        ``num ``=` `A[i]`   `        ``if` `(num ``%` `2` `=``=` `0``):` `            ``even[num ``%` `K] ``=` `1` `        ``else``:` `            ``odd[num ``%` `K] ``=` `1`   `    ``# Stores the maximum` `    ``# remainder obtained` `    ``max_rem ``=` `0`   `    ``# Find the complement of remainder` `    ``# of each even number in odd set` `    ``for` `x ``in` `even:` `        `  `        ``# Find the complement` `        ``# of remainder x` `        ``y ``=` `K ``-` `1` `-` `x` `        ``od ``=` `list``(odd.keys())` `        ``it ``=` `bisect_left(od, y)` `        `  `        ``if` `(it !``=` `0``):` `            ``max_rem ``=` `max``(max_rem, x ``+` `od[it])` `            `  `    ``# Print the answer` `    ``print` `(max_rem)`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``# Given array` `    ``arr ``=` `[``3``, ``2``, ``4``, ``11``, ``6``, ``7``]`   `    ``# Size of the array` `    ``N ``=` `len``(arr)`   `    ``# Given value of K` `    ``K ``=` `7`   `    ``maxRemainder(arr, N, K)` `    `  `# This code is contributed by mohit kumar 29`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{` `    ``// Function to find the maximum` `    ``// remainder of sum of a pair` `    ``// of array elements modulo K` `    ``static` `void` `MaxRemainder(``int``[] A, ``int` `N, ``int` `K)` `    ``{` `        ``// Stores all even numbers` `        ``HashSet<``int``> even = ``new` `HashSet<``int``>();`   `        ``// Stores all odd numbers` `        ``SortedSet<``int``> odd = ``new` `SortedSet<``int``>();`   `        ``// Segregate remainders of even` `        ``// and odd numbers in respective sets` `        ``foreach` `(``int` `num ``in` `A)` `        ``{` `            ``if` `(num % 2 == 0)` `                ``even.Add(num % K);` `            ``else` `                ``odd.Add(num % K);` `        ``}`   `        ``// Stores the maximum` `        ``// remainder obtained` `        ``int` `max_rem = 0;`   `        ``// Find the complement of remainder` `        ``// of each even number in odd set` `        ``foreach` `(``int` `x ``in` `even)` `        ``{` `            ``// Find the complement` `            ``// of remainder x` `            ``int` `y = K - 1 - x;` `            ``if` `(odd.Min <= y)` `                ``max_rem = Math.Max(max_rem, x + (``int``)odd.GetViewBetween(``int``.MinValue, y).Max);` `        ``}`   `        ``// Print the answer` `        ``Console.Write(max_rem);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``// Given array` `        ``int``[] arr = { 3, 2, 4, 11, 6, 7 };`   `        ``// Size of the array` `        ``int` `N = arr.Length;`   `        ``// Given value of K` `        ``int` `K = 7;`   `        ``MaxRemainder(arr, N, K);` `    ``}` `}`   `// This code is contributed by phasing17`

## Javascript

 `// JavaScript program for the above approach`   `// Function to find the upper bound of an array. ` `function` `upper_bound(arr, X)` `{` `    ``let mid;` ` `  `    ``// Initialise starting index and` `    ``// ending index` `    ``let low = 0;` `    ``let high = arr.length;` ` `  `    ``// Till low is less than high` `    ``while` `(low < high) {` `        ``// Find the middle index` `        ``mid = low + Math.floor((high - low) / 2);` ` `  `        ``// If X is greater than or equal` `        ``// to arr[mid] then find` `        ``// in right subarray` `        ``if` `(X >= arr[mid]) {` `            ``low = mid + 1;` `        ``}` ` `  `        ``// If X is less than arr[mid]` `        ``// then find in left subarray` `        ``else` `{` `            ``high = mid;` `        ``}` `    ``}` `   `  `    ``// if X is greater than arr[n-1]` `    ``if``(low < N && arr[low] <= X) {` `       ``low++;` `    ``}` ` `  `    ``// Return the upper_bound index` `    ``return` `low;` `}`   `// Function to find the maximum` `// remainder of sum of a pair` `// of array elements modulo K` `function` `maxRemainder(A, N, K)` `{` `    `  `    ``// Stores all even numbers` `    ``let even = ``new` `Array();`   `    ``// Stores all odd numbers` `    ``let odd = ``new` `Array();`   `    ``// Segregate remainders of even` `    ``// and odd numbers in respective sets` `    ``for``(let i = 0; i < N; i++) ` `    ``{` `        ``let num = A[i];` `        `  `        ``if` `(num % 2 == 0 && !even.includes(num%K)){` `            ``even.push(num % K);` `        ``}     ` `        ``else` `if``(num%2 != 0 && !odd.includes(num%K)){` `            ``odd.push(num % K);` `        ``}   ` `    ``}`   `    ``odd.sort();` `    ``// Stores the maximum` `    ``// remainder obtained` `    ``let max_rem = 0;`   `    ``// Find the complement of remainder` `    ``// of each even number in odd set` `    ``for``(let i = 0;i < even.length; i++){` `        ``let x = even[i];` `        ``// Find the complement` `        ``// of remainder xd` `        ``// console.log(x);` `        ``let y = K - 1 - x;`   `        ``let it = upper_bound(odd, y);` `        ``if` `(it != 0) ` `        ``{` `            ``it--;` `            ``max_rem = Math.max(max_rem, x + odd[it]);` `        ``}` `    ``}`   `    ``// Print the answer` `    ``console.log(max_rem);` `}`   `// Driver code` `// Given array` `let arr = [3, 2, 4, 11, 6, 7];`   `// Size of the array` `let N = arr.length;`   `// Given value of K` `let K = 7;`   `maxRemainder(arr, N, K);`     `// This code is contributed by Nidhi goel`

Output:

`6`

Time Complexity: O(N * logN)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next