Minimum operations required to make all Array elements divisible by K | Python3 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
from collections import defaultdict NEW_LINE def compute ( a , N , K ) : NEW_LINE INDENT eqVal = defaultdict ( int ) NEW_LINE maxX = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = a [ i ] % K NEW_LINE if ( val != 0 ) : NEW_LINE INDENT val = K - val NEW_LINE DEDENT if ( val == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( val in eqVal ) : NEW_LINE INDENT numVal = eqVal [ val ] NEW_LINE maxX = max ( maxX , val + ( K * numVal ) ) NEW_LINE eqVal [ val ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT eqVal [ val ] += 1 NEW_LINE maxX = max ( maxX , val ) NEW_LINE DEDENT DEDENT if maxX == 0 : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( maxX + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 3 NEW_LINE a = [ 1 , 2 , 2 , 18 ] NEW_LINE N = len ( a ) NEW_LINE compute ( a , N , K ) NEW_LINE DEDENT