Array element with minimum sum of absolute differences | Set 2 | C ++ program for the above approach ; Function to find the element with minimum sum of differences between any elements in the array ; Stores the required X and sum of absolute differences ; Calculate sum of array elements ; The sum of absolute differences can 't be greater than sum ; Update res that gives the minimum sum ; If the current difference is less than the previous difference ; Update min_diff and res ; Print the resultant value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumDiff ( int arr [ ] , int N ) { int res = arr [ 0 ] , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; int min_diff = sum ; for ( int i = 0 ; i < N ; i ++ ) { if ( abs ( sum - ( arr [ i ] * N ) ) < min_diff ) { min_diff = abs ( sum - ( arr [ i ] * N ) ) ; res = arr [ i ] ; } } cout << res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumDiff ( arr , N ) ; return 0 ; }