Count the replacements
int dif = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] != dup [ i % 3 ] ) dif ++ ; mini = min ( mini , dif ) ; } while ( next_permutation ( dup . begin ( ) , dup . end ( ) ) ) ;