Magnetic Force Between Two Balls
Medium
Topics
Given an array nums of distinct basket positions and an integer target (= m balls), place the balls into baskets so that the minimum distance between any two balls is as large as possible. Return that maximum possible minimum distance.
Example 1
Input: nums = [1,2,3,4,7], target = 3 Output: 3
Example 2
Input: nums = [5,4,3,2,1,1000000000], target = 2 Output: 999999999
Constraints
- 2 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^9
- All positions are distinct.
- 2 <= target <= nums.length
Editorial — intuition, approach, complexity and pitfalls
Intuition
We place m balls in given positions so that the minimum gap between any two is as large as possible. Choosing which positions to use directly is combinatorial; the way in is to search the answer instead.
Guess a minimum gap d and ask the easier question: can we place m balls with every pair at least d apart? Greedily — sort the positions, take the first, then take each next position that is at least d beyond the last one taken. Taking the earliest feasible position always leaves the most room behind it, so this maximises how many balls fit.
The count of placeable balls is non-increasing in d, which is the monotonicity binary search needs. So search d over [1, max - min] and keep the largest feasible value.
💡 Same shape as "divide chocolate" and "ship packages within D days": binary search on the answer with a linear greedy feasibility check. The giveaway is "maximise the minimum".
Approach
- Sort the positions — the greedy requires order.
- Binary search
dover[1, max - min]. - For each
d, greedily count placeable balls; if it reachesm, recorddand try larger.
Dry Run
position = [1,2,3,4,7], m = 3
sorted [1,2,3,4,7], lo=1 hi=6
mid=3 place 1, next >= 4 -> 4, next >= 7 -> 7 3 balls feasible, ans=3, lo=4
mid=5 place 1, next >= 6 -> 7 2 balls short, hi=4
mid=4 place 1, next >= 5 -> 7 2 balls short, hi=3
lo > hi
answer 3 (balls at 1, 4, 7 -- minimum gap 3)Complexity
- Time — O(n log(max)): the sort is O(n log n) and each of about 30 probes is a linear pass.
- Space — O(log n) in Java and C++, O(n) in Python, all of it the sort. The greedy check holds two counters — and note it must iterate by index rather than slicing
positions[1:], which would copy the array on every probe.
Common Pitfalls
- Forgetting to sort. The greedy depends entirely on ascending order.
- Slicing inside the feasibility check. It runs once per probe, so an O(n) copy there is paid thirty times over.
- Using
>instead of>=for the gap test, which rejects a placement that exactly meets the target. - Starting
loat 0. A gap of 0 is always feasible and wastes a probe; worse, it muddies the invariant that every candidate is a real distance. - Binary searching the number of balls rather than the gap. The ball count is the constraint; the gap is the unknown.
Full Solution — all languages
class Solution:
def maxDistance(self, nums, target):
nums.sort()
n = len(nums)
def ok(d):
# Index loop, not `for p in nums[1:]`: that slice copies the array on
# every binary-search probe, which is both O(n) space and O(n) wasted
# copying per iteration.
cnt, last = 1, nums[0]
for i in range(1, n):
if nums[i] - last >= d:
cnt += 1
last = nums[i]
return cnt
lo, hi, ans = 1, nums[-1] - nums[0], 0
while lo <= hi:
mid = lo + (hi - lo) // 2
if ok(mid) >= target:
ans = mid
lo = mid + 1
else:
hi = mid - 1
return ansimport java.util.*;
class Solution {
public int maxDistance(int[] nums, int target) {
Arrays.sort(nums);
int lo = 1, hi = nums[nums.length - 1] - nums[0], ans = 0;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (ok(nums, mid) >= target) {
ans = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return ans;
}
int ok(int[] nums, int d) {
int cnt = 1, last = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] - last >= d) {
cnt++;
last = nums[i];
}
}
return cnt;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxDistance(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int lo = 1, hi = nums.back() - nums.front(), ans = 0;
auto ok = [&](int d) {
int cnt = 1, last = nums[0];
for (size_t i = 1; i < nums.size(); i++) {
if (nums[i] - last >= d) {
cnt++;
last = nums[i];
}
}
return cnt;
};
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (ok(mid) >= target) {
ans = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return ans;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var maxDistance = function(nums, target) {
nums.sort((a, b) => a - b);
let lo = 1, hi = nums[nums.length - 1] - nums[0], ans = 0;
const ok = (d) => {
let cnt = 1, last = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] - last >= d) {
cnt++;
last = nums[i];
}
}
return cnt;
};
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (ok(mid) >= target) {
ans = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return ans;
};