712303. Minimize Max Distance to Gas Station

Hard

Here is the generated Markdown blog post:

Minimize Max Distance to Gas Station

Summary

The problem requires you to find a gas station with the minimum maximum distance from all other gas stations. Given an array of integers representing the positions of gas stations, your goal is to minimize the maximum distance between any two stations.

Tags: Binary Search, Mathematical, Arrays, Data Structures, Algorithms

Difficulty: Hard

Detailed Explanation

The problem involves finding a set of gas stations that are spaced as evenly as possible. To achieve this, we'll use binary search to find the optimal solution.

Here's a step-by-step breakdown of the algorithm:

  1. First, sort the array of gas station positions in ascending order.
  2. Initialize two variables: left and right. Set left to 0 (the first element in the sorted array) and right to the last element in the array.
  3. Perform a binary search to find the optimal distance between gas stations.
  4. In each iteration of the binary search, calculate the total distance traveled if we were to space the gas stations at a distance equal to (left + right) / 2. This is calculated by iterating through the sorted array and adding up the distances between consecutive gas stations, using the midpoint as the spacing for all gas stations.
  5. If the total distance traveled in step 4 is less than or equal to right - left, update right to (left + right) / 2. This means that we've found a better spacing, and we should narrow our search range to the left half of the current interval.
  6. Otherwise, update left to (left + right) / 2 + 1. This means that we haven't found a better spacing yet, so we should widen our search range to the right half of the current interval.
  7. Repeat steps 4-6 until right - left is less than or equal to 1.
  8. The optimal distance between gas stations is now (left + right) / 2.

Time complexity: O(n log n), where n is the number of gas stations. Space complexity: O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public int minMaxDistance(int[] positions) {
    Arrays.sort(positions);
    int left = 0, right = positions.length - 1;
    while (right - left > 1) {
        int mid = (left + right) / 2;
        long totalDistance = 0;
        for (int i = 0; i < positions.length - 1; i++) {
            totalDistance += Math.abs(positions[i + 1] - positions[i]) - mid;
        }
        if (totalDistance <= 0) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return (int)((left + right) / 2);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.