Difference between sum of K maximum even and odd array elements | Java program for the above approach ; Function to find the absolute difference between sum of first K maximum even and odd numbers ; Stores index from where odd number starts ; Segregate even and odd number ; If current element is even ; Sort in decreasing order even part ; Sort in decreasing order odd part ; Calculate sum of k maximum even number ; Calculate sum of k maximum odd number ; Print the absolute difference ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
import java . util . * ; class GFG { static void evenOddDiff ( int a [ ] , int n , int k ) { int j = - 1 ; Vector < Integer > even = new Vector < > ( ) ; Vector < Integer > odd = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) { even . add ( a [ i ] ) ; } else odd . add ( a [ i ] ) ; } j ++ ; Collections . sort ( even ) ; Collections . reverse ( even ) ; Collections . sort ( odd ) ; Collections . reverse ( odd ) ; int evenSum = 0 , oddSum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { evenSum += even . get ( i ) ; } for ( int i = 0 ; i < k ; i ++ ) { oddSum += odd . get ( i ) ; } System . out . print ( Math . abs ( evenSum - oddSum ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 8 , 3 , 4 , 5 } ; int N = arr . length ; int K = 2 ; evenOddDiff ( arr , N , K ) ; } }