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