Make all array elements equal with minimum cost | This function assumes that a [ ] is sorted . If a [ ] is not sorted , we need to sort it first . ; If there are odd elements , we choose middle element ; If there are even elements , then we choose the average of middle two . ; After deciding the final value , find the result . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCostToMakeElementEqual ( int a [ ] , int n ) { int y ; if ( n % 2 == 1 ) y = a [ n / 2 ] ; else y = ( a [ n / 2 ] + a [ ( n - 2 ) / 2 ] ) / 2 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) s += abs ( a [ i ] - y ) ; return s ; } int main ( ) { int a [ ] = { 1 , 100 , 101 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( minCostToMakeElementEqual ( a , n ) ) ; }