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 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.
Examples
Example 1:
|
|
|
|
Example 2:
|
|
Solution
The problem is to distribute m
balls into n
baskets such that the minimum magnetic force between any two balls is maximized. The idea is to determine the maximum possible minimum distance between any two balls when they are placed in the baskets.
Method 1 - Binary Search
Lets take inputs position = [1,2,3,4,7], m = 3
, these are the steps we can follow:
- Sort the Positions: First, sort the baskets’ positions.
position = [1,2,3,4,7]
- Binary Search on the Answer: Use binary search to find the maximum possible minimum force.
- The lower bound
lo
is 1 ⇨ min possible force - The upper bound
hi
is(position[n - 1] - position[0]) / (m - 1)
⇨ max possible force. Using example,hi = (7 - 1)/2 = 3
. We divide bym-1
, because the force happens between2
adjacent balls, hence form
balls, we will havem - 1
forces as per above question.
- The lower bound
- Greedy Check: For each mid value in the binary search, use a greedy algorithm to check if it’s possible to place the
m
balls such that the minimum distance between any two balls is at leastmid
. Lets see how:- Iteration 1:
low = 1, high = 3
⇨ mid = 4 / 2 = 2. Now, we try to keepm = 3
balls, such that distance between these force isminForce = 2
.- Keep first ball at position 1, then we keep 2nd ball at position
3
which has, and then we keep7
. - Since we managed to keep the balls with
minForce = 2
, lets try to maximize it a bit. So,low = mid + 1 = 3
- Keep first ball at position 1, then we keep 2nd ball at position
- Iteration 2:
low = 3, high = 3
⇨mid = 3
. Now, we try to keepm = 3
balls, such that distance between these force isminForce = 3
.- Keep first ball at position
1
, then we keep 2nd ball at position4
, and then third ball at position7
. - Since we managed to keep the balls with
minForce = 3
, lets try to maximize it a bit. So,low = mid + 1 = 4
- Keep first ball at position
- Now,
low > mid
, hence we come out of the loop, andminForce = 3
.
- Iteration 1:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n * log (max - min))
, wheren
is the number of baskets and(max - min)
is the range of positions. - 🧺 Space complexity:
O(1)