Skip to content

Commit c72eb41

Browse files
authored
Create 1552. Magnetic Force Between Two Balls (#509)
2 parents c39c4ae + c14da5b commit c72eb41

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:
3+
int maxDistance(vector<int>& position, int m) {
4+
sort(position.begin(),position.end());
5+
int l = 0;
6+
int r = static_cast<int>((position[position.size()-1] - position[l])/(m-1));
7+
int res = 0;
8+
while(l<=r){
9+
int mid = (l+r)/2;
10+
if(isPossible(position, m, mid)){
11+
res = mid;
12+
l = mid + 1;
13+
}else{
14+
r = mid - 1;
15+
}
16+
}
17+
return res;
18+
}
19+
bool isPossible(vector<int>& position, int m, int mid){
20+
if(mid == 0)return true;
21+
int i=0;
22+
while(i<position.size()){
23+
int start = position[i];
24+
while(i<position.size() && position[i]<start+mid){
25+
i++;
26+
}
27+
if(i<position.size() && position[i]>=start+mid)m--;
28+
}
29+
if(m <= 1)return true;
30+
return false;
31+
}
32+
};

0 commit comments

Comments
 (0)