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.
思路:以后记住,minimax的题目,基本上都是binary search + greedy helper function。这题转弯的地方在于,如何求给定distance的情况下,计算需要多少个ball。
node个数: n......2
distance:mindistance....maxdistance;
注意: if(needput(mid, position) >= m) 这里是>=m; 题目要求最大,首先判断end,再判断start;
注意:helper function,起始点是1开始的,原因是开头其实点,必须先放一个ball;
class Solution {
public int maxDistance(int[] position, int m) {
int curmin = Integer.MAX_VALUE;
int n = position.length;
Arrays.sort(position);
for(int i = 0; i < n - 1; i++) {
curmin = Math.min(curmin, position[i + 1] - position[i]);
}
int start = curmin; int end = position[n - 1] - position[0];
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(needballs(position, mid) >= m) {
start = mid;
} else {
end = mid;
}
}
if(needballs(position, end) >= m) {
return end;
}
return start;
}
private int needballs(int[] position, int distance) {
int count = 1; // 刚开始起始点,必须放一个球;
int lastindex = 0;
for(int i = 0; i < position.length; i++) {
if(position[i] - position[lastindex] >= distance) {
count++;
lastindex = i;
}
}
return count;
}
}