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 Code
< ? php function arraySum ( $ arr , $ n ) { $ sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ sum = $ sum + $ arr [ $ i ] ; return $ sum ; } function maxDiff ( $ arr , $ n , $ k ) { sort ( $ arr ) ; $ arraysum = arraySum ( $ arr , $ n ) ; $ diff1 = abs ( $ arraysum - 2 * arraySum ( $ arr , $ k ) ) ; array_reverse ( $ arr ) ; $ diff2 = abs ( $ arraysum - 2 * arraySum ( $ arr , $ k ) ) ; return ( max ( $ diff1 , $ diff2 ) ) ; } $ arr = array ( 1 , 7 , 4 , 8 , -1 , 5 , 2 , 1 ) ; $ n = count ( $ arr ) ; $ k = 3 ; echo " Maximum ▁ Difference ▁ = ▁ " , maxDiff ( $ arr , $ n , $ k ) ; ? >