Traverse from the back of map so as to take bigger elements first
for ( Map . Entry < Integer , Integer > u : count . descendingMap ( ) . entrySet ( ) ) { int j = u . getKey ( ) ; int x = j * count . get ( j ) ; if ( d <= x ) { k += ( d + j - 1 ) / j ; break ; } k += count . get ( j ) ; d -= x ; } }