Magnetic Force Between Two Balls - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
position = [1,2,3,4,7], m = 3
›
Output:
3
💡 Note:
Place balls at positions 1, 4, and 7. The minimum distance between any two balls is min(|4-1|, |7-4|, |7-1|) = min(3, 3, 6) = 3.
Example 2 — Closer Positions
$
Input:
position = [5,4,3,2,1,1000000000], m = 2
›
Output:
999999999
💡 Note:
Place balls at positions 1 and 1000000000. The distance between them is |1000000000 - 1| = 999999999, which is the maximum possible minimum distance.
Example 3 — All Balls Must Fit
$
Input:
position = [1,2,8,4,9], m = 4
›
Output:
1
💡 Note:
After sorting positions = [1,2,4,8,9]. To place 4 balls, we can place them at positions 1, 2, 4, 8 with minimum distance = 1.
Constraints
- 2 ≤ n ≤ 105
- 1 ≤ m ≤ n
- 1 ≤ position[i] ≤ 109
- All position[i] are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of basket positions and number of balls to place
2
Process
Find optimal placement to maximize minimum distance
3
Output
Maximum possible minimum distance
Key Takeaway
🎯 Key Insight: Use binary search on the answer space - if we can achieve distance X, we can achieve any smaller distance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code