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