Array element with minimum sum of absolute differences | C ++ implementation of the approach ; Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int x = arr [ n / 2 ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += abs ( arr [ i ] - x ) ; return sum ; } int main ( ) { int arr [ ] = { 1 , 3 , 9 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minSum ( arr , n ) ; return 0 ; }