You are given a 0-indexed integer arraystations of length n, where stations[i] represents the number of power stations in the ith city.
Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r, then a power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1.
Note:|x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7.
The power of a city is the total number of power stations it is being provided power from.
The government has sanctioned building k more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.
Given the two integers r and k, return the maximum possible minimum power of a city, if the additional power stations are built optimally.
Note that you can build the k power stations in multiple cities.
Input & Output
Example 1 — Basic Case
$Input:stations = [1,2,4,5,0], r = 1, k = 3
›Output:5
💡 Note:Initial powers: [3,7,11,9,5]. With k=3 stations optimally placed, we can achieve minimum power of 5 across all cities.
Example 2 — Small Range
$Input:stations = [4,4,4,4], r = 0, k = 3
›Output:4
💡 Note:With r=0, each station only powers its own city. We have 3 additional stations to distribute, but can't improve minimum power beyond 4.
Example 3 — Large Range
$Input:stations = [1,2,4,5,6], r = 2, k = 5
›Output:11
💡 Note:With r=2, each station covers 5 cities. Strategic placement of 5 additional stations can achieve minimum power of 11.
The key insight is to binary search on the answer (minimum power value) and use a greedy strategy to verify if it's achievable. For each candidate minimum power, greedily place additional stations as far right as possible within range when cities fall below the target. Best approach is Binary Search + Greedy with Time: O(n log(sum+k)), Space: O(n).
Common Approaches
✓
Optimized
⏱️ Time: N/A
Space: N/A
Binary Search on Answer + Greedy Verification
⏱️ Time: O(n log(sum+k))
Space: O(n)
Binary search on the answer space (minimum power value). For each candidate answer, greedily place stations to verify if we can achieve that minimum power with exactly k additional stations.
Brute Force - Try All Placements
⏱️ Time: O(n^k × n × r)
Space: O(k)
Generate all possible ways to place k additional stations across n cities, calculate the resulting power for each city in every configuration, and return the maximum minimum power found.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static long long additional[100005];
static long long power[100005];
int canAchieve(int* stations, int n, int r, long long k, long long minPower) {
memset(additional, 0, n * sizeof(long long));
long long used = 0;
long long currentAdditional = 0;
// Initialize window sum for additional stations
int window_end = (n < r + 1) ? n : r + 1;
for (int i = 0; i < window_end; i++) {
currentAdditional += additional[i];
}
for (int i = 0; i < n; i++) {
if (i > 0) {
// Update sliding window for additional stations
if (i + r < n) {
currentAdditional += additional[i + r];
}
if (i - r - 1 >= 0) {
currentAdditional -= additional[i - r - 1];
}
}
long long currentPower = power[i] + currentAdditional;
if (currentPower < minPower) {
long long needed = minPower - currentPower;
used += needed;
if (used > k) {
return 0;
}
// Place stations at rightmost position to help future cities
int pos = (i + r < n - 1) ? i + r : n - 1;
additional[pos] += needed;
currentAdditional += needed;
}
}
return 1;
}
long long maxPowerSolution(int* stations, int n, int r, long long k) {
// Calculate initial power for each city
long long currentSum = 0;
// Initialize window for first city
int window_end = (n < r + 1) ? n : r + 1;
for (int i = 0; i < window_end; i++) {
currentSum += stations[i];
}
power[0] = currentSum;
// Calculate power for remaining cities using sliding window
for (int i = 1; i < n; i++) {
// Add right element if within bounds
if (i + r < n) {
currentSum += stations[i + r];
}
// Remove left element if it goes out of range
if (i - r - 1 >= 0) {
currentSum -= stations[i - r - 1];
}
power[i] = currentSum;
}
// Binary search on the answer
long long left = 0;
long long right = k;
for (int i = 0; i < n; i++) {
right += stations[i];
}
long long result = 0;
while (left <= right) {
long long mid = left + (right - left) / 2;
if (canAchieve(stations, n, r, k, mid)) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
char* endptr;
long val = strtol(p, &endptr, 10);
if (endptr != p) {
arr[(*size)++] = (int)val;
p = endptr;
} else {
break;
}
}
}
int main() {
char line[100000];
if (!fgets(line, sizeof(line), stdin)) return 1;
int stations[100000];
int n = 0;
parseArray(line, stations, &n);
int r;
if (scanf("%d", &r) != 1) return 1;
long long k;
if (scanf("%lld", &k) != 1) return 1;
long long result = maxPowerSolution(stations, n, r, k);
printf("%lld\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
⚡ Linearithmic
Space Complexity
n
2n
⚡ Linearithmic Space
15.2K Views
MediumFrequency
~35 minAvg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.