LeetCode 2528: Maximize the Minimum Powered City

Problem Description

Explanation:

To solve this problem, we can use binary search to find the maximum possible minimum power of a city. We can start with a lower bound of 0 and an upper bound of the maximum number of power stations in any city. For each mid value between the lower and upper bounds, we can simulate the process of adding k power stations and check if it is possible to achieve a minimum power of at least mid by using the greedy approach to distribute the additional power stations optimally.

Here are the detailed steps:

  1. Initialize the lower bound as 0 and the upper bound as the maximum number of power stations in any city.
  2. Perform binary search to find the maximum possible minimum power of a city.
  3. Within each iteration of the binary search, simulate the process of adding k power stations and distributing them optimally to maximize the minimum power.
  4. Use a greedy approach to allocate the k power stations by targeting the cities with the least power first.
  5. Check if it is possible to achieve a minimum power of at least mid by adding k power stations.

Time Complexity:

The time complexity of this approach is O(n * log(maxPower)), where n is the number of cities and maxPower is the maximum number of power stations in any city.

Space Complexity:

The space complexity is O(1) as we are not using any extra space apart from a few variables.

:

Solutions

class Solution {
    public int maximizeMinimum(int[] stations, int r, int k) {
        int n = stations.length;
        int lower = 0;
        int upper = Arrays.stream(stations).max().getAsInt();
        
        while (lower < upper) {
            int mid = (upper - lower) / 2 + lower;
            if (!possibleToAchieveMinimum(stations, r, k, mid)) {
                lower = mid + 1;
            } else {
                upper = mid;
            }
        }
        
        return lower;
    }
    
    private boolean possibleToAchieveMinimum(int[] stations, int r, int k, int minPower) {
        int[] additionalStations = new int[stations.length];
        int additional = k;
        
        for (int i = 0; i < stations.length; i++) {
            if (stations[i] < minPower) {
                int need = minPower - stations[i];
                if (need > additional) {
                    return false;
                }
                additionalStations[i] = need;
                additional -= need;
            }
        }
        
        for (int i = 0; i < stations.length; i++) {
            if (additionalStations[i] > 0) {
                for (int j = Math.max(0, i - r); j <= Math.min(stations.length - 1, i + r); j++) {
                    additionalStations[j] = Math.max(additionalStations[j], additionalStations[i]);
                }
            }
        }
        
        return true;
    }
}

Loading editor...