Minimum operations to make counts of remainders same in an array | Java 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
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int minOperations ( int n , int a [ ] , int m ) { int k = n / m ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] val = new Vector [ m ] ; for ( int i = 0 ; i < val . length ; i ++ ) val [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { val [ a [ i ] % m ] . add ( i ) ; } long ans = 0 ; Vector < pair > extra = new Vector < > ( ) ; for ( int i = 0 ; i < 2 * m ; ++ i ) { int cur = i % m ; while ( ( val [ cur ] . size ( ) ) > k ) { int elem = val [ cur ] . lastElement ( ) ; val [ cur ] . removeElementAt ( val [ cur ] . size ( ) - 1 ) ; extra . add ( new pair ( elem , i ) ) ; } while ( val [ cur ] . size ( ) < k && ! extra . isEmpty ( ) ) { int elem = extra . get ( extra . size ( ) - 1 ) . first ; int mmod = extra . get ( extra . size ( ) - 1 ) . second ; extra . remove ( extra . size ( ) - 1 ) ; val [ cur ] . add ( elem ) ; ans += i - mmod ; } } return ( int ) ans ; } public static void main ( String [ ] args ) { int m = 3 ; int a [ ] = { 3 , 2 , 0 , 6 , 10 , 12 } ; int n = a . length ; System . out . print ( minOperations ( n , a , m ) ) ; } }