Minimize increment / decrement of Array elements to make each modulo K equal | C # 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
using System ; using System . Collections . Generic ; class GFG { static int Find_min ( HashSet < int > diff_mod , Dictionary < int , int > count_mod , int k ) { int min_oprn = int . MaxValue ; int oprn = 0 ; for ( int x = 0 ; x < k ; x ++ ) { oprn = 0 ; foreach ( int w in diff_mod ) { if ( w != x ) { if ( w == 0 ) { oprn += Math . Min ( x , k - x ) * count_mod [ w ] ; } else { oprn += Math . Min ( Math . Abs ( x - w ) , k + x - w ) * count_mod [ w ] ; } } } if ( oprn < min_oprn ) min_oprn = oprn ; } return min_oprn ; } static int Cal_min ( int [ ] arr , int n , int k ) { HashSet < int > diff_mod = new HashSet < int > ( ) ; Dictionary < int , int > count_mod = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { diff_mod . Add ( arr [ i ] % k ) ; if ( count_mod . ContainsKey ( ( arr [ i ] % k ) ) ) count_mod [ arr [ i ] % k ] = count_mod [ ( arr [ i ] % k ) ] + 1 ; else count_mod . Add ( arr [ i ] % k , 1 ) ; } return Find_min ( diff_mod , count_mod , k ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 35 , 48 , 23 , 52 } ; int n = arr . Length ; int k = 3 ; Console . Write ( Cal_min ( arr , n , k ) ) ; } }