Update those rows which lead to maximum score after toggle
foreach ( KeyValuePair < int , int > it in update ) if ( K > 0 ) { int idx = it . Value ; for ( int j = 0 ; j < m ; ++ j ) A [ idx , j ] = ( A [ idx , j ] + 1 ) % 2 ; K -- ; }