There are n baskets on a line, and basket i sits at integer coordinate position[i]. You have m balls to put into the baskets. The magnetic force between two balls at positions x and y is |x - y|.
Choose where the balls go so that the minimum magnetic force between any two balls is as large as possible, and return that largest possible minimum force.
Function Signature
def max_distance(position: list[int], m: int) -> int:
Rules
-
Each basket holds at most one ball, so the
m
balls go into
m
different baskets.
-
position
is not necessarily sorted.
-
The return value is a single integer: the minimum pairwise force of the best placement.
Constraints
-
n == len(position)
-
2 <= n <= 10^5
-
1 <= position[i] <= 10^9
-
All integers in
position
are distinct.
-
2 <= m <= len(position)
Examples
Input: position = [1,2,3,4,7], m = 3
Output: 3
Putting the balls at 1, 4 and 7 gives forces 3, 3 and 6, so the minimum is 3. A minimum of 4 is impossible: after a ball at 1, the next ball must be at 7 or beyond, and nothing is left for the third ball.
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
With two balls, the best choice is the two extreme baskets, 1 and 1000000000, which are 999999999 apart.
Input: position = [10,3,7], m = 3
Output: 3
Every basket must be used. Sorted, the positions are 3, 7 and 10, and the closest pair is 7 and 10 with force 3.