Maximum difference between group of k | CPP to find maximum group difference ; utility function for array sum ; function for finding maximum group difference of array ; sort the array ; find array sum ; difference for k - smallest diff1 = ( arraysum - k_smallest ) - k_smallest ; reverse array for finding sum 0f 1 st k - largest ; difference for k - largest diff2 = ( arraysum - k_largest ) - k_largest ; return maximum difference value ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int arraySum ( int arr [ ] , int n ) { long long int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + arr [ i ] ; return sum ; } long long int maxDiff ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; long long int arraysum = arraySum ( arr , n ) ; long long int diff1 = abs ( arraysum - 2 * arraySum ( arr , k ) ) ; reverse ( arr , arr + n ) ; long long int diff2 = abs ( arraysum - 2 * arraySum ( arr , k ) ) ; return ( max ( diff1 , diff2 ) ) ; } int main ( ) { int arr [ ] = { 1 , 7 , 4 , 8 , -1 , 5 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << " Maximum ▁ Difference ▁ = ▁ " << maxDiff ( arr , n , k ) ; return 0 ; }