forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximize-the-minimum-powered-city.cpp
62 lines (59 loc) · 1.88 KB
/
maximize-the-minimum-powered-city.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Time: O(nlogk)
// Space: O(n)
// binary search, sliding window, greedy
class Solution {
public:
long long maxPower(vector<int>& stations, int r, int k) {
const auto& min_power = [&]() {
int64_t mn = numeric_limits<int64_t>::max();
int64_t curr = accumulate(cbegin(stations), cbegin(stations) + r, 0ll);
for (int i = 0; i < size(stations); ++i) {
if (i + r < size(stations)) {
curr += stations[i + r];
}
if (i >= r + 1) {
curr -= stations[i - (r + 1)];
}
mn = min(mn, curr);
}
return mn;
};
const int64_t mn = min_power();
const auto& check = [&](int64_t target) {
vector<int> arr(cbegin(stations), cend(stations));
int64_t curr = accumulate(cbegin(arr), cbegin(arr) + r, 0ll);
int cnt = k;
for (int i = 0; i < size(arr); ++i) {
if (i + r < size(arr)) {
curr += arr[i + r];
}
if (i >= r + 1) {
curr -= arr[i - (r + 1)];
}
if (curr >= target) {
continue;
}
const auto diff = target - curr;
if (diff > cnt) {
return false;
}
cnt -= diff;
curr += diff;
if (i + r < size(arr)) {
arr[i + r] += diff;
}
}
return true;
};
int64_t left = mn, right = mn + k;
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (!check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
};