Minimize increment / decrement of Array elements to make each modulo K equal | Python3 program for the above approach ; 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 ; Function call to return value of min oprn required ; Driver Code
import sys NEW_LINE from collections import defaultdict NEW_LINE def Find_min ( diff_mod , count_mod , k ) : NEW_LINE INDENT min_oprn = sys . maxsize NEW_LINE oprn = 0 NEW_LINE for x in range ( k ) : NEW_LINE INDENT oprn = 0 NEW_LINE for w in diff_mod : NEW_LINE INDENT if ( w != x ) : NEW_LINE INDENT if ( w == 0 ) : NEW_LINE INDENT oprn += ( min ( x , k - x ) * count_mod [ w ] ) NEW_LINE DEDENT else : NEW_LINE INDENT oprn += ( min ( abs ( x - w ) , k + x - w ) * count_mod [ w ] ) NEW_LINE DEDENT DEDENT DEDENT if ( oprn < min_oprn ) : NEW_LINE INDENT min_oprn = oprn NEW_LINE DEDENT DEDENT return min_oprn NEW_LINE DEDENT def Cal_min ( arr , n , k ) : NEW_LINE INDENT diff_mod = set ( [ ] ) NEW_LINE count_mod = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT diff_mod . add ( arr [ i ] % k ) NEW_LINE count_mod [ arr [ i ] % k ] += 1 NEW_LINE DEDENT return Find_min ( diff_mod , count_mod , k ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 35 , 48 , 23 , 52 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( Cal_min ( arr , n , k ) ) NEW_LINE DEDENT