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
def minCostToMakeElementEqual ( a ) : NEW_LINE INDENT l = len ( a ) NEW_LINE if ( l % 2 == 1 ) : NEW_LINE INDENT y = a [ l // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT y = ( a [ l // 2 ] + a [ ( l - 2 ) // 2 ] ) // 2 NEW_LINE DEDENT s = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT s += abs ( a [ i ] - y ) NEW_LINE DEDENT return s NEW_LINE DEDENT a = [ 1 , 100 , 101 ] NEW_LINE print ( minCostToMakeElementEqual ( a ) ) NEW_LINE