Upper bound returns pointer to position of next higher number than a [ i ] + mid in a [ i . . n - 1 ] . We subtract ( ub + i + 1 ) from this position to count
int ub = upperbound ( a , n , a [ i ] + mid ) ; res += ( ub - ( i - 1 ) ) ; } return res ; }