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
def arraySum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maxDiff ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arraysum = arraySum ( arr , n ) NEW_LINE diff1 = abs ( arraysum - 2 * arraySum ( arr , k ) ) NEW_LINE arr . reverse ( ) NEW_LINE diff2 = abs ( arraysum - 2 * arraySum ( arr , k ) ) NEW_LINE return ( max ( diff1 , diff2 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 7 , 4 , 8 , - 1 , 5 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Maximum ▁ Difference ▁ = " , maxDiff ( arr , n , k ) ) NEW_LINE DEDENT