Maximum difference between group of k | 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
function arraySum ( arr , n ) { var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) sum = sum + arr [ i ] ; return sum ; } function maxDiff ( arr , n , k ) { arr . sort ( ( a , b ) => a - b ) ; var arraysum = arraySum ( arr , n ) ; var diff1 = Math . abs ( arraysum - 2 * arraySum ( arr , k ) ) ; arr . reverse ( ) ; var diff2 = Math . abs ( arraysum - 2 * arraySum ( arr , k ) ) ; return ( Math . max ( diff1 , diff2 ) ) ; } var arr = [ 1 , 7 , 4 , 8 , - 1 , 5 , 2 , 1 ] ; var n = arr . length ; var k = 3 ; document . write ( " " + maxDiff ( arr , n , k ) ) ;