Leetcode 1552. Magnetic Force Between Two Balls
In 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, 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 = , m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs . The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = , m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position <= 10^9
All integers in position are distinct.
2 <= m <= position.length
class Solution:
def maxDistance(self, position: List, m: int) -> int:
position.sort()
N = len(position)
left, right = 0, position[-1] - position
while left + 1 < right:
mid = int((right - left) / 2 + left)
if self.count(mid, position) >= m:
left = mid
else:
right = mid
if self.count(right, position) == m:
return right
return left
def count(self, n: int, position: List) -> int:
ans, curr = 1, position
for i in range(1, len(position)):
if position - curr >= n:
curr = position
ans += 1
return ans
页:
[1]