Sort in non - increasing order of difference
sort ( v . begin ( ) , v . end ( ) , [ & ] ( pair < int , int > a , pair < int , int > b ) { return ( a . first - a . second ) > ( b . first - b . second ) ; } ) ; int i = 0 ; while ( sum > K && i < v . size ( ) ) { sum -= ( v [ i ] . first - v [ i ] . second ) ; i ++ ; } if ( sum <= K ) return i ; return -1 ; }