Checking for all possibility
int set1 = i ; int set2 = K - i ; if ( greaterE . size ( ) >= set1 && lessE . size ( ) >= set2 ) { int step1 = 0 ; int step2 = 0 ; for ( int j = 0 ; j < set1 ; j ++ ) step1 += greaterE . get ( j ) ; for ( int j = 0 ; j < set2 ; j ++ ) step2 += lessE . get ( j ) ; mi = Math . min ( mi , Math . max ( step1 , step2 ) ) ; } } System . out . println ( mi ) ; } }