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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Find_min ( set < int > & diff_mod , map < int , int > count_mod , int k ) { int min_oprn = INT_MAX ; int oprn = 0 ; for ( int x = 0 ; x < k ; x ++ ) { oprn = 0 ; for ( auto w : diff_mod ) { if ( w != x ) { if ( w == 0 ) { oprn += min ( x , k - x ) * count_mod [ w ] ; } else { oprn += min ( abs ( x - w ) , k + x - w ) * count_mod [ w ] ; } } } if ( oprn < min_oprn ) min_oprn = oprn ; } return min_oprn ; } int Cal_min ( int arr [ ] , int n , int k ) { set < int > diff_mod ; map < int , int > count_mod ; for ( int i = 0 ; i < n ; i ++ ) { diff_mod . insert ( arr [ i ] % k ) ; count_mod [ arr [ i ] % k ] ++ ; } return Find_min ( diff_mod , count_mod , k ) ; } int main ( ) { int arr [ ] = { 2 , 35 , 48 , 23 , 52 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << Cal_min ( arr , n , k ) ; return 0 ; }