Magnetic Force Between Two Balls LeetCode solution in Java

1
class Solution {
2
public int maxDistance(int[] position, int m) {
3
Arrays.sort(position);
4
int low = Integer.MAX_VALUE;
5
int high = 0;
6
for (int i = 1; i < position.length; i++) {
7
low = Math.min(low, position[i] - position[i - 1]);
8
}
9
high = position[position.length - 1] - position[0];
10
int ans = -1;
11
while (low <= high) {
12
int mid = low + (high - low) / 2;
13
if (blackbox(mid, position, m)) {
14
ans = mid;
15
low = mid + 1;
16
} else {
17
high = mid - 1;
18
}
19
}
20
return ans;
21
}
22

23
public boolean blackbox(int maxPossibleDist, int[] position, int m) {
24
int balls = 1;
25
int prevballplace = position[0];
26
for (int i = 1; i < position.length; i++) {
27
if (position[i] - prevballplace >= maxPossibleDist) {
28
prevballplace = position[i];
29
balls++;
30
}
31
}
32
if (balls >= m) {
33
return true;
34
}
35
return false;
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0