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[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.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
- All integers in
position
are distinct. 2 <= m <= position.length
Solution: Binary Search
Find the max distance that we can put m balls.
Time complexity: O(n*log(distance))
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Solution { public: int maxDistance(vector<int>& position, int m) { const int n = position.size(); sort(begin(position), end(position)); auto count = [&](int d) -> int { int last = position[0]; int ans = 1; for (int x : position) { if (x - last >= d) { last = x; ++ans; } } return ans; }; int l = 0; int t = (position.back() - position.front()) + 1; int r = t; while (l < r) { int mid = l + (r - l) / 2; if (count(t - mid) >= m) // find min of l => max of t - l r = mid; else l = mid + 1; } return t - l; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Solution { public int maxDistance(int[] position, int m) { Arrays.sort(position); final int n = position.length; int l = 0; int r = position[n - 1] - position[0] + 1; int t = r; while (l < r) { int mid = l + (r - l) / 2; if (getCount(position, t - mid) >= m) r = mid; else l = mid + 1; } return t - l; } private int getCount(int[] position, int d) { int count = 1; int last = position[0]; for (int x : position) { if (x - last >= d) { ++count; last = x; } } return count; } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution: def maxDistance(self, position: List[int], m: int) -> int: position.sort() def getCount(d: int) -> int: last, count = position[0], 1 for x in position: if x - last >= d: last = x count += 1 return count l, r = 0, position[-1] - position[0] + 1 t = r while l < r: mid = l + (r - l) // 2 if getCount(t - mid) >= m: r = mid else: l = mid + 1 return t - l |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment