Minimize Max Distance to Gas Station

On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = stations.length.

Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized.

Return the smallest possible value of D.

Example:

Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000

Note:

  1. stations.length will be an integer in range [10, 2000].
  2. stations[i] will be an integer in range [0, 10^8].
  3. K will be an integer in range [1, 10^6].
  4. Answers within 10^-6 of the true value will be accepted as correct.

思路:就是如果加入0个station,那么上限就是现在的max adjcent distance, 如果加入无穷多个station,那么下限就是distance = 0;那么就是要找到恰当的dis 使得加入的station是K,那么就是个二分答案的binary search,辅助方程是求给你distance,求要加入多少个stations. 求station 个数就用station[i] - station[i-1] / dis 注意double的判断,不用用start + 1 < end,要用eps = 1e-6 , start + eps < end来判断;

class Solution {
    public double minmaxGasDist(int[] stations, int k) {
        if(stations == null || stations.length == 0) {
            return 0.0;
        }
        double start = 0;
        double end = 0;
        for(int i = 1; i < stations.length; i++) {
            end = Math.max(end, stations[i] - stations[i - 1]);
        }
        double eps = 1e-6;
        while(start + eps < end) {
            double mid = start + (end - start) / 2;
            if(canfit(mid, stations) > k) {
                start = mid;
            } else {
                end = mid;
            }
        }
        if(canfit(start, stations) > k) {
            return end;
        }
        return start;
    }
    
    private int canfit(double distance, int[] stations) {
        int count = 0;
        for(int i = 1; i < stations.length; i++) {
            double diff = stations[i] - stations[i - 1];
            count += diff / distance;
        }
        return count;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值