โ† Back to Index

๐Ÿ“š Minimize Max Distance to Gas Station โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Minimize Max Distance to Gas Station problem involves placing additional gas stations along a highway to minimize the maximum distance between adjacent stations. The goal is to determine the smallest possible maximum distance using binary search.

๐Ÿงฑ Pattern Template

class Solution {
    public double minmaxGasDist(int[] stations, int k) {
        double left = 0, right = stations[stations.length - 1] - stations[0];

        while (right - left > 1e-6) {
            double mid = left + (right - left) / 2;

            if (canPlace(stations, k, mid)) {
                right = mid; // Try a smaller maximum distance
            } else {
                left = mid; // Try a larger maximum distance
            }
        }

        return left;
    }

    private boolean canPlace(int[] stations, int k, double maxDist) {
        int count = 0;

        for (int i = 1; i < stations.length; i++) {
            count += (int) ((stations[i] - stations[i - 1]) / maxDist);

            if (count > k) {
                return false;
            }
        }

        return true;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Minimize Max Distance to Gas Station

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

Explanation:
- Place 9 additional stations to minimize the maximum distance to 0.5.

๐Ÿ’ก Pro Tips