Sort in non - increasing order of difference
v . sort ( key = lambda a : a [ 0 ] - a [ 1 ] ) NEW_LINE i = 0 NEW_LINE while ( sum > K and i < len ( v ) ) : NEW_LINE INDENT sum -= ( v [ i ] [ 0 ] - v [ i ] [ 1 ] ) NEW_LINE i += 1 NEW_LINE DEDENT if ( sum <= K ) : NEW_LINE INDENT return i NEW_LINE DEDENT return - 1 NEW_LINE