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[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:

Magnetic Force Between Two Balls_第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;

class Solution {
    public int maxDistance(int[] position, int m) {
        if(position == null || position.length == 0) {
            return 0;
        }
        int n = position.length;
        Arrays.sort(position);
        
        int min = Integer.MAX_VALUE;
        int max = position[n - 1] - position[0];
        for(int i = 0; i < n - 1; i++) {
            min = Math.min(min, position[i + 1] - position[i]);
        }
            
        int start = min; int end = max;
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(needput(mid, position) >= m) {
                start = mid;
            } else {
                //needput(mid, position) < m
                end = mid;
            }
        }
        
        if(needput(end, position) >= m) {
            return end;
        }
        return start;
    }
    
    private int needput(int distance, int[] position) {
        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;
    }
}

 

你可能感兴趣的:(二分答案)