1515. Power Grid Floor
A city has n towns in a row, and stations[i] power stations stand in town i. The power of town i is the total number of stations in all towns j with |i - j| <= r. You may build up to k new stations, each only in a town where allowed[i] is '1' (several may share a town).
Return the largest possible value of the minimum power over all towns, as a long. Binary search the target floor X and sweep left to right with a difference array: when town i falls short, place the whole deficit at the rightmost allowed town no further than i + r, failing if that town lies before i - r or the total used exceeds k. Target O(n log(n * max + k)) time and O(n) extra space.
Example 1
- Input:
- stations = [1,2,4,5,0]r = 1allowed = "11111"k = 2
- Output:
- 5
- Explanation:
Building both new stations in the first town lifts its power from 3 to 5, and the weakest town now has power 5; reaching 6 would need four stations.
Example 2
- Input:
- stations = [4,4,4]r = 0allowed = "000"k = 100
- Output:
- 4
- Explanation:
With r = 0 and no allowed town nothing can be built, so the weakest town stays at 4.
Example 3
- Input:
- stations = [0,0,0]r = 1allowed = "010"k = 5
- Output:
- 5
- Explanation:
Only the middle town is allowed, and a station there powers all three towns, raising every power to 5.
Constraints
1 ≤ n ≤ 105; allowed.length == n over {'0','1'}; 0 ≤ stations[i] ≤ 105; 0 ≤ r < n; 0 ≤ k ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(n log(n * max + k))
- Space
- O(n)