Maximize remainder of sum of a pair of array elements with different parity modulo K | Java 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
import java . util . * ; class GFG { static void maxRemainder ( int A [ ] , int N , int K ) { HashSet < Integer > even = new HashSet < > ( ) ; TreeSet < Integer > odd = new TreeSet < > ( ) ; for ( int num : A ) { if ( num % 2 == 0 ) even . add ( num % K ) ; else odd . add ( num % K ) ; } int max_rem = 0 ; for ( int x : even ) { int y = K - 1 - x ; if ( odd . floor ( y ) != null ) max_rem = Math . max ( max_rem , x + odd . floor ( y ) ) ; } System . out . print ( max_rem ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 11 , 6 , 7 } ; int N = arr . length ; int K = 7 ; maxRemainder ( arr , N , K ) ; } }