Minimum operations of given type to make all elements of a matrix equal | Java implementation of the approach ; Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; will not work for negative elements , so . . adding this ; adding this to handle negative elements too . ; 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 . ; changed here as in case of even elements there will be 2 medians ; Return minimum operations required ; Driver code
import java . util . * ; class GFG { public static int minOperations ( int n , int m , int k , int matrix [ ] [ ] ) { Vector < Integer > arr = new Vector < > ( ) ; int mod ; if ( matrix [ 0 ] [ 0 ] < 0 ) { mod = k - ( Math . abs ( matrix [ 0 ] [ 0 ] ) % k ) ; } else { mod = matrix [ 0 ] [ 0 ] % k ; } for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < m ; ++ j ) { arr . add ( matrix [ i ] [ j ] ) ; int val = matrix [ i ] [ j ] ; if ( val < 0 ) { int res = k - ( Math . abs ( val ) % k ) ; if ( res != mod ) { return - 1 ; } } else { int foo = matrix [ i ] [ j ] ; if ( foo % k != mod ) { return - 1 ; } } } } Collections . sort ( arr ) ; int median = arr . get ( ( n * m ) / 2 ) ; int minOperations = 0 ; for ( int i = 0 ; i < n * m ; ++ i ) minOperations += Math . abs ( arr . get ( i ) - median ) / k ; if ( ( n * m ) % 2 == 0 ) { int median2 = arr . get ( ( ( n * m ) / 2 ) - 1 ) ; int minOperations2 = 0 ; for ( int i = 0 ; i < n * m ; ++ i ) minOperations2 += Math . abs ( arr . get ( i ) - median2 ) / k ; minOperations = Math . min ( minOperations , minOperations2 ) ; } return minOperations ; } public static void main ( String [ ] args ) { int matrix [ ] [ ] = { { 2 , 4 , 6 } , { 8 , 10 , 12 } , { 14 , 16 , 18 } , { 20 , 22 , 24 } } ; int n = matrix . length ; int m = matrix [ 0 ] . length ; int k = 2 ; System . out . println ( minOperations ( n , m , k , matrix ) ) ; } }