[LeetCode] Magnetic Force Between Two Balls

1552. Magnetic Force Between Two Balls

In the 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int search(vector<int>& p, int m) {
int res = 1;
for(int i = 1, last = p[0]; i < p.size(); i++) {
if(last + m > p[i]) continue;
last = p[i];
res++;
}
return res;
}
public:
int maxDistance(vector<int>& p, int k) {
sort(begin(p), end(p));
int l = 1, r = p.back() - p[0];
while(l <= r) {
int m = l + (r - l) / 2;
int s = search(p, m);
if(s >= k) l = m + 1;
else r = m - 1;
}
return r;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/27/PS/LeetCode/magnetic-force-between-two-balls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.