Sum of minimum absolute difference of each array element | function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; Driver code
def sumOfMinAbsDifferences ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE sum += abs ( arr [ 0 ] - arr [ 1 ] ) ; NEW_LINE sum += abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT sum += min ( abs ( arr [ i ] - arr [ i - 1 ] ) , abs ( arr [ i ] - arr [ i + 1 ] ) ) NEW_LINE DEDENT return sum ; NEW_LINE DEDENT arr = [ 5 , 10 , 1 , 4 , 8 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum ▁ = ▁ " , sumOfMinAbsDifferences ( arr , n ) ) NEW_LINE