Minimum operations to make counts of remainders same in an array | C ++ implementation of the approach ; Function to return the minimum number of operations required ; To store modulos values ; If it 's size greater than k  it needed to be decreased ; If it 's size is less than k  it needed to be increased ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int n , int a [ ] , int m ) { int k = n / m ; vector < vector < int > > val ( m ) ; for ( int i = 0 ; i < n ; ++ i ) { val [ a [ i ] % m ] . push_back ( i ) ; } long long ans = 0 ; vector < pair < int , int > > extra ; for ( int i = 0 ; i < 2 * m ; ++ i ) { int cur = i % m ; while ( int ( val [ cur ] . size ( ) ) > k ) { int elem = val [ cur ] . back ( ) ; val [ cur ] . pop_back ( ) ; extra . push_back ( make_pair ( elem , i ) ) ; } while ( int ( val [ cur ] . size ( ) ) < k && ! extra . empty ( ) ) { int elem = extra . back ( ) . first ; int mmod = extra . back ( ) . second ; extra . pop_back ( ) ; val [ cur ] . push_back ( elem ) ; ans += i - mmod ; } } return ans ; } int main ( ) { int m = 3 ; int a [ ] = { 3 , 2 , 0 , 6 , 10 , 12 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minOperations ( n , a , m ) ; return 0 ; }