## 题目

#### 5489. Magnetic Force Between Two Balls

In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

Given the integer array position and the integer m. Return the required force.

Constraints:

n == position.length 2 <= n <= 10^5 1 <= position[i] <= 10^9 All integers in position are distinct. 2 <= m <= position.length

## 解法

class Solution {
public:
bool check(vector<int>& position, int dist,int m){
int cnt = 1;
int l = position[0];
for(int i=1;i<position.size();++i){
if(position[i] - l >= dist){
cnt++;
if(cnt >= m) return true;
l = position[i];
}
}
return cnt >= m;
}
int maxDistance(vector<int>& position, int m) {
sort(position.begin(),position.end());
int down = 1;
int up = (position.back() - position[0])/(m-1);
int ans = 0;
while(down <= up){
int mid = down + (up-down)/2;
if(check(position,mid,m)){
ans = mid;
down = mid+1;
}else{
up = mid-1;
}
}
return ans;
}
};