Minimum operations required to make all Array elements divisible by K | Java implementation to find the minimum number of moves required to update the array such that each of its element is 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
import java . util . * ; class GFG { static void compute ( int a [ ] , int N , int K ) { Map < Long , Long > eqVal = new HashMap < Long , Long > ( ) ; long maxX = 0 ; for ( int i = 0 ; i < N ; i ++ ) { long val = a [ i ] % K ; val = ( val == 0 ? 0 : K - val ) ; if ( val == 0 ) continue ; if ( eqVal . containsKey ( val ) ) { long numVal = eqVal . get ( val ) ; maxX = Math . max ( maxX , val + ( K * numVal ) ) ; eqVal . put ( val , eqVal . getOrDefault ( val , 0l ) + 1l ) ; } else { eqVal . put ( val , 1l ) ; maxX = Math . max ( maxX , val ) ; } } System . out . println ( maxX == 0 ? 0 : maxX + 1 ) ; } public static void main ( String [ ] args ) { int K = 3 ; int a [ ] = { 1 , 2 , 2 , 18 } ; int N = a . length ; compute ( a , N , K ) ; } }