-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagnetic_Force_Between_Two_Balls.java
More file actions
52 lines (51 loc) · 1.25 KB
/
Magnetic_Force_Between_Two_Balls.java
File metadata and controls
52 lines (51 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
import java.io.*;
import java.lang.*;
public class Magnetic_Force_Between_Two_Balls {
class Solution {
public int maxDistance(int[] position, int m) {
int n = position.length;
Arrays.sort(position);
int l = 0;
int h = position[n-1];
int mid = 0;
int ans = 0;
while(l<=h)
{
mid = l + (h - l)/2;
if(valid(mid , position , m))
{
ans = mid;
l = mid+1;
}
else
{
h = mid-1;
}
}
return ans;
}
private boolean valid(int gap , int[] a , int m)
{
int prev = a[0];
int placed = 1;
for(int i = 1 ; i<a.length ; i++)
{
if(a[i] - prev >= gap)
{
prev = a[i];
placed++;
}
if(placed == m)
{
return true;
}
}
if(placed < m)
{
return false;
}
return true;
}
}
}