Minimum operations required to make all Array elements divisible by K | Function to find the minimum number of moves required to update the array such that each of its element is divisible by K ; Initialize Map data structure ; Iterate for all the elements of the array ; Calculate the value to be added ; Check if the value equals to 0 then simply continue ; Check if the value to be added is present in the map ; Update the answer ; Print the required result We need to add 1 to maxX because we cant ignore the first move where initially X = 0 and we need to increase it by 1 to make some changes in array ; Driver code
function compute ( a , N , K ) { let eqVal = new Map ( ) ; let maxX = 0 ; for ( let i = 0 ; i < N ; i ++ ) { let val = a [ i ] % K ; val = ( val == 0 ? 0 : K - val ) ; if ( val == 0 ) continue ; if ( eqVal . has ( val ) ) { let numVal = eqVal . get ( val ) ; maxX = Math . max ( maxX , val + ( K * numVal ) ) ; eqVal . set ( val , eqVal . get ( val ) + 1 ) ; } else { eqVal . set ( val , 1 ) ; maxX = Math . max ( maxX , val ) ; } } document . write ( maxX == 0 ? 0 : maxX + 1 ) ; } let K = 3 ; let a = [ 1 , 2 , 2 , 18 ] ; let N = a . length ; compute ( a , N , K ) ;