I am confused about the terminating condition of the loop in binary search. I have also seen some solutions where high - low > 1
is used. I need some explanations to understand when to use low < high
, low <= high
and high - low > 1
.
class Solution {
public static int maxValueArray(int n, int k, int[] arr) {
long l = Arrays.stream(arr).min().getAsInt() - 1;
long r = 1_000_000_001;
while (r - l > 1) {
long m = (l + r) / 2;
long extra = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > m)
extra += (arr[i] - m) / k;
else
extra -= (m - arr[i]);
}
if (extra >= 0)
l = m;
else
r = m;
}
return (int)l;
}
}
Here is the solution from the editorial where I changed the condition of while to l < r
but that did not work
New contributor
Biks is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.