Difference between sum of K maximum even and odd array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void evenOddDiff ( int a [ ] , int n , int k ) { int j = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) { j ++ ; swap ( a [ i ] , a [ j ] ) ; } } j ++ ; sort ( a , a + j , greater < int > ( ) ) ; sort ( a + j , a + n , greater < int > ( ) ) ; int evenSum = 0 , oddSum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { evenSum += a [ i ] ; } for ( int i = j ; i < ( j + k ) ; i ++ ) { oddSum += a [ i ] ; } cout << abs ( evenSum - oddSum ) ; } int main ( ) { int arr [ ] = { 1 , 8 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; evenOddDiff ( arr , N , K ) ; return 0 ; }