Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 865f81f

Browse files
authored
Create Magnetic Force Between Two Balls.java
1 parent afa6897 commit 865f81f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int maxDistance(int[] position, int m) {
3+
int result = 0;
4+
int n = position.length;
5+
Arrays.sort(position);
6+
int left = 1;
7+
int right = (int) Math.ceil(position[n - 1] / (m - 1.0));
8+
while (left <= right) {
9+
int mid = (left + right) / 2;
10+
if (isPossible(position, mid, m)) {
11+
result = mid;
12+
left = mid + 1;
13+
} else {
14+
right = mid - 1;
15+
}
16+
}
17+
return result;
18+
}
19+
20+
private boolean isPossible(int[] position, int distance, int m) {
21+
int prevBall = position[0];
22+
int ballCount = 1;
23+
for (int i = 1; i < position.length && ballCount < m; i++) {
24+
int curr = position[i];
25+
if (curr - prevBall >= distance) {
26+
ballCount++;
27+
prevBall = curr;
28+
}
29+
}
30+
return ballCount == m;
31+
}
32+
}

0 commit comments

Comments
 (0)