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:

 

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值