Minimize increment / decrement of Array elements to make each modulo K equal | Function to find the minimum operations required to make the modulo of each element of the array equal to each other ; Variable to store minimum operation required ; To store operation required to make all modulo equal ; Iterating through all possible modulo value ; Iterating through all different modulo obtained so far ; Calculating oprn required to make all modulos equal to x ; Checking the operations that will cost less ; Check operation that will cost less ; Update the minimum number of operations ; Returning the answer ; Function to store different modulos ; Set to store all different modulo ; Map to store count of all different modulo obtained ; Storing all different modulo count ; Insert into the set ; Increment count Increment count ; Function call to return value of min oprn required ; Driver Code
function Find_min ( diff_mod , count_mod , k ) { let min_oprn = Number . MAX_VALUE ; let oprn = 0 ; for ( let x = 0 ; x < k ; x ++ ) { oprn = 0 ; for ( let w of diff_mod . values ( ) ) { if ( w != x ) { if ( w == 0 ) { oprn += Math . min ( x , k - x ) * count_mod . get ( w ) ; } else { oprn += Math . min ( Math . abs ( x - w ) , k + x - w ) * count_mod . get ( w ) ; } } } if ( oprn < min_oprn ) min_oprn = oprn ; } return min_oprn ; } function Cal_min ( arr , n , k ) { let diff_mod = new Set ( ) ; let count_mod = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { diff_mod . add ( arr [ i ] % k ) ; if ( count_mod . has ( ( arr [ i ] % k ) ) ) count_mod . set ( arr [ i ] % k , count_mod . get ( arr [ i ] % k ) + 1 ) ; else count_mod . set ( arr [ i ] % k , 1 ) ; } return Find_min ( diff_mod , count_mod , k ) ; } let arr = [ 2 , 35 , 48 , 23 , 52 ] ; let n = arr . length ; let k = 3 ; document . write ( Cal_min ( arr , n , k ) ) ;