Magnetic Force Between Two Balls Problem
Description
LeetCode Problem 1552.
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 i^th 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.
Example 1:

Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length2 <= n <= 10^51 <= position[i] <= 10^9- All integers in
positionare distinct. 2 <= m <= position.length
Solution
Approach: Binary Search on the Answer
Turn the question around: given a gap g, can we place all m balls so that every two balls are at least g apart? This is easy to answer greedily on the sorted positions. Put the first ball in the leftmost basket, then walk right and drop a ball into each basket that is at least g past the last ball. Placing each ball as early as possible never hurts, because it leaves the most room for the balls after it. If the greedy places at least m balls, g is achievable.
The check is monotone: if a gap g works, every smaller gap works too. So binary search for the largest gap that works:
- The smallest candidate is
1(positions are distinct). - The largest is
(max - min) / (m - 1):mballs makem - 1gaps inside a span ofmax - min, and the smallest gap cannot exceed their average.
Use the upper midpoint (lo + hi + 1) / 2 when moving lo = mid, otherwise the search can loop forever on two values.
Complexity: O(n log n + n log R) time, where R is the span of the positions, and O(n) extra space for the sorted copy (O(log n) if sorting in place).
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position = sorted(position)
def fits(gap: int) -> bool:
# Greedy: put a ball in the first basket, then in every basket at least `gap` past the last ball.
count, last = 1, position[0]
for p in position[1:]:
if p - last >= gap:
count += 1
last = p
return count >= m
lo, hi = 1, (position[-1] - position[0]) // (m - 1) # hi is the best gap we could hope for
while lo < hi:
mid = (lo + hi + 1) // 2
if fits(mid):
lo = mid
else:
hi = mid - 1
return lo