774. Minimize Max Distance to Gas Station

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

Now, we addKmore gas stations so thatD, the maximum distance between adjacent gas stations, is minimized.

Return the smallest possible value ofD.

Example:

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

Output:
 0.500000

Heap

class Solution {
    public double minmaxGasDist(int[] stations, int K) {
        int N = stations.length;
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) ->
            (double)b[0]/b[1] < (double)a[0]/a[1] ? -1 : 1);
        for (int i = 0; i < N-1; ++i)
            pq.add(new int[]{stations[i+1] - stations[i], 1});

        for (int k = 0; k < K; ++k) {
            int[] node = pq.poll();
            node[1]++;
            pq.add(node);
        }

        int[] node = pq.poll();
        return (double)node[0] / node[1];
    }
}

TLE

Binary Search

class Solution {
    public double minmaxGasDist(int[] stations, int K) {
        double lo = 0, hi = 1e8;
        while (hi - lo > 1e-6) {
            double mi = (lo + hi) / 2.0;
            if (possible(mi, stations, K))
                hi = mi;
            else
                lo = mi;
        }
        return lo;
    }

    public boolean possible(double D, int[] stations, int K) {
        int used = 0;
        for (int i = 0; i < stations.length - 1; ++i)
            used += (int) ((stations[i+1] - stations[i]) / D);
        return used <= K;
    }
}

results for ""

    No results matching ""