Sum of minimum absolute difference of each array element | C ++ implementation to find the 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 program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfMinAbsDifferences ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int sum = 0 ; sum += abs ( arr [ 0 ] - arr [ 1 ] ) ; sum += abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) sum += min ( abs ( arr [ i ] - arr [ i - 1 ] ) , abs ( arr [ i ] - arr [ i + 1 ] ) ) ; return sum ; } int main ( ) { int arr [ ] = { 5 , 10 , 1 , 4 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ = ▁ " << sumOfMinAbsDifferences ( arr , n ) ; }