Minimum operations of given type to make all elements of a matrix equal | Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; If not possible ; Sort the array to get median ; To count the minimum operations ; If there are even elements , then there are two medians . We consider the best of two as answer . ; Return minimum operations required ; Driver code
def minOperations ( n , m , k , matrix ) : NEW_LINE INDENT arr = [ 0 ] * ( n * m ) NEW_LINE mod = matrix [ 0 ] [ 0 ] % k NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT arr [ i * m + j ] = matrix [ i ] [ j ] NEW_LINE if matrix [ i ] [ j ] % k != mod : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT arr . sort ( ) NEW_LINE median = arr [ ( n * m ) // 2 ] NEW_LINE minOperations = 0 NEW_LINE for i in range ( 0 , n * m ) : NEW_LINE INDENT minOperations += abs ( arr [ i ] - median ) // k NEW_LINE DEDENT if ( n * m ) % 2 == 0 : NEW_LINE INDENT median2 = arr [ ( ( n * m ) // 2 ) - 1 ] NEW_LINE minOperations2 = 0 NEW_LINE for i in range ( 0 , n * m ) : NEW_LINE INDENT minOperations2 += abs ( arr [ i ] - median2 ) // k NEW_LINE DEDENT minOperations = min ( minOperations , minOperations2 ) NEW_LINE DEDENT return minOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 2 , 4 , 6 ] , [ 8 , 10 , 12 ] , [ 14 , 16 , 18 ] , [ 20 , 22 , 24 ] ] NEW_LINE n = len ( matrix ) NEW_LINE m = len ( matrix [ 0 ] ) NEW_LINE k = 2 NEW_LINE print ( minOperations ( n , m , k , matrix ) ) NEW_LINE DEDENT