Leet Code Daily 2024-06-20 - Magnetic Force Between Two Balls
Solution
Binary search.
Code
class Solution {
public:
// Given `position` sorted in increasing order and `min_dis`,
// returns the maximum number of balls possible.
int maxBalls(vector<int>& position, int min_dis) {
int prev_pos = position[0], ret = 1;
for (int i = 1; i < position.size(); i++) {
if (position[i] - prev_pos >= min_dis) {
prev_pos = position[i];
ret++;
}
}
return ret;
}
int maxDistance(vector<int>& position, int m) {
sort(position.begin(), position.end());
int low = 0, high = position[position.size() - 1] - position[0];
while (low < high) {
int mid = (low + high) / 2 + 1;
if (maxBalls(position, mid) >= m) {
low = mid;
} else {
high = mid - 1;
}
}
return low;
}
};