#1552
Medium Algorithms Magnetic force between two balls
Array Binary Search Sorting
71.9% acceptance
Feb 25, 2026
3180
272
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn max_distance(mut position: Vec<i32>, m: i32) -> i32 {
position.sort();
let n = position.len();
// Binary search on the answer (minimum distance)
let can_place = |min_dist: i32| -> bool {
let mut count = 1;
let mut last = position[0];
for i in 1..n {
if position[i] - last >= min_dist {
count += 1;
last = position[i];
if count >= m { return true; }
}
}
false
};
let mut lo = 1i32;
let mut hi = position[n-1] - position[0];
while lo < hi {
let mid = lo + (hi - lo + 1) / 2;
if can_place(mid) { lo = mid; } else { hi = mid - 1; }
}
lo
}
}