Skip to content

Commit bd574e2

Browse files
authored
Create maximize-the-minimum-powered-city.py
1 parent 16500ac commit bd574e2

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: O(nlogk)
2+
# Space: O(n)
3+
4+
# binary search, sliding window, greedy
5+
class Solution(object):
6+
def maxPower(self, stations, r, k):
7+
"""
8+
:type stations: List[int]
9+
:type r: int
10+
:type k: int
11+
:rtype: int
12+
"""
13+
def min_power():
14+
mn = float("inf")
15+
curr = sum(stations[i] for i in xrange(r))
16+
for i in xrange(len(stations)):
17+
if i+r < len(stations):
18+
curr += stations[i+r]
19+
if i >= r+1:
20+
curr -= stations[i-(r+1)]
21+
mn = min(mn, curr)
22+
return mn
23+
24+
def check(target):
25+
arr = stations[:]
26+
curr = sum(arr[i] for i in xrange(r))
27+
cnt = k
28+
for i in xrange(len(arr)):
29+
if i+r < len(arr):
30+
curr += arr[i+r]
31+
if i >= r+1:
32+
curr -= arr[i-(r+1)]
33+
if curr >= target:
34+
continue
35+
d = target-curr
36+
if d > cnt:
37+
return False
38+
cnt -= d
39+
curr += d
40+
if i+r < len(arr):
41+
arr[i+r] += d
42+
return True
43+
44+
mn = min_power()
45+
left, right = mn, mn+k
46+
while left <= right:
47+
mid = left + (right-left)//2
48+
if not check(mid):
49+
right = mid-1
50+
else:
51+
left = mid+1
52+
return right
53+

0 commit comments

Comments
 (0)