#2528
Maximize the Minimum Powered City
HardArrayBinary SearchGreedyQueueSliding WindowPrefix SumBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max(stations) + k)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log(max(stations) + k))Space O(n)
The optimal approach uses binary search to find the maximum possible minimum power of any city after optimally distributing the additional power stations. This is efficient and leverages the properties of the problem.
⚙️
Algorithm
3 steps- 1Step 1: Define a function to check if a given minimum power can be achieved by distributing the k power stations.
- 2Step 2: Use binary search to find the maximum minimum power by checking midpoints and adjusting the search range based on feasibility.
- 3Step 3: For each midpoint, calculate how many additional power stations are needed to ensure every city has at least that power.
solution.py29 lines
1# Full working Python code
2
3def canAchievePower(stations, r, k, target):
4 n = len(stations)
5 needed = 0
6 power = [0] * n
7 for i in range(n):
8 if power[i] < target:
9 add = target - power[i]
10 needed += add
11 if needed > k:
12 return False
13 for j in range(max(0, i - r), min(n, i + r + 1)):
14 power[j] += add
15 return True
16
17
18def maxMinPower(stations, r, k):
19 left, right = 0, max(stations) + k
20 while left < right:
21 mid = (left + right + 1) // 2
22 if canAchievePower(stations, r, k, mid):
23 left = mid
24 else:
25 right = mid - 1
26 return left
27
28# Example usage
29print(maxMinPower([1, 2, 4, 5, 0], 1, 2))ℹ
Complexity note: The time complexity is O(n log(max(stations) + k)) because we perform a binary search over the possible power values and for each value, we check if it can be achieved in O(n) time.
- 1Understanding how power stations affect multiple cities is crucial.
- 2Binary search can efficiently narrow down the maximum minimum power.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.