Skip to content

Commit e6f563a

Browse files
committed
Time: 1006 ms (96.91%), Space: 29.5 MB (72.16%) - LeetHub
1 parent 153b451 commit e6f563a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# time complexity: O(nlogD)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def maxPower(self, stations: List[int], r: int, k: int) -> int:
8+
n = len(stations)
9+
count = [0] * (n + 1)
10+
11+
for i in range(n):
12+
left = max(0, i - r)
13+
right = min(n, i + r + 1)
14+
count[left] += stations[i]
15+
count[right] -= stations[i]
16+
17+
def check(val: int) -> bool:
18+
diff = count.copy()
19+
total = 0
20+
remaining = k
21+
22+
for i in range(n):
23+
total += diff[i]
24+
if total < val:
25+
add = val - total
26+
if remaining < add:
27+
return False
28+
remaining -= add
29+
end = min(n, i + 2 * r + 1)
30+
diff[end] -= add
31+
total += add
32+
return True
33+
34+
leftIdx, rightIdx = min(stations), sum(stations) + k
35+
result = 0
36+
while leftIdx <= rightIdx:
37+
midIdx = (leftIdx + rightIdx) // 2
38+
if check(midIdx):
39+
result = midIdx
40+
leftIdx = midIdx + 1
41+
else:
42+
rightIdx = midIdx - 1
43+
return result
44+
45+
46+
stations = [1, 2, 4, 5, 0]
47+
r = 1
48+
k = 2
49+
print(Solution().maxPower(stations, r, k))
50+
stations = [4, 4, 4, 4]
51+
r = 0
52+
k = 3
53+
print(Solution().maxPower(stations, r, k))

0 commit comments

Comments
 (0)