Maximize difference between the sum of absolute differences of each element with the remaining array | Function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; Sort the array in ascending order ; Stores prefix sum at any instant ; Store the total array sum ; Initialize minimum and maximum absolute difference ; Traverse the array to find the total array sum ; Traverse the array arr [ ] ; Store the number of elements to its left ; Store the number of elements to its right ; Update the sum of elements on its left ; Store the absolute difference sum ; Update the Minimum ; Update the Maximum ; Update sum of elements on its left ; Prthe result ; Driven Code
def findMaxDifference ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE Leftsum = 0 NEW_LINE Totalsum = 0 NEW_LINE Min , Max = 10 ** 8 , - 10 ** 8 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Totalsum += arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT leftNumbers = i NEW_LINE rightNumbers = n - i - 1 NEW_LINE Totalsum = Totalsum - arr [ i ] NEW_LINE sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) NEW_LINE Min = min ( Min , sum ) NEW_LINE Max = max ( Max , sum ) NEW_LINE Leftsum += arr [ i ] NEW_LINE DEDENT print ( Max - Min ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE findMaxDifference ( arr , N ) NEW_LINE DEDENT