Minimum operations required to make all Array elements divisible by K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void compute ( int a [ ] , int N , int K ) { map < long , long > eqVal ; 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 . find ( val ) != eqVal . end ( ) ) { long numVal = eqVal [ val ] ; maxX = max ( maxX , val + ( K * numVal ) ) ; eqVal [ val ] ++ ; } else { eqVal [ val ] ++ ; maxX = max ( maxX , val ) ; } } cout << ( maxX == 0 ? 0 : maxX + 1 ) << endl ; } int main ( ) { int K = 3 ; int a [ ] = { 1 , 2 , 2 , 18 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; compute ( a , N , K ) ; return 0 ; }