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
import java . io . * ; import java . util . * ; class GFG { public static 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 += Math . abs ( a [ i ] - y ) ; return s ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 100 , 101 } ; int n = a . length ; System . out . println ( minCostToMakeElementEqual ( a , n ) ) ; } }