In original problem "each friend is guaranteed to have distinct amount of money", so duplicated amounts of money will not occur in test cases. The issue in attached code is different, consider for example following test case:
1
1 42
21
Additionally if I am reading attached binary search correctly, then hi
represents an index past-the-end, so check for empty range is not lo > hi
, but rather lo >= hi
.
There is also potential signed integer overflow in m - arr[i]
given that money can be negative.
On the other hand, if you are asking how to solve a version of this problem where duplicates are allowed, then you could run a binary search twice to determine a whole range of elements that are equal to given. Determine position of first element that is not smaller than x (C++ lower_bound), and position of first element that is greater than x (C++ upper_bound), together those describe a closed-open range of elements that are equal to x (potentially an empty one).