-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
earliest-second-to-mark-indices-ii.cpp
50 lines (48 loc) · 1.69 KB
/
earliest-second-to-mark-indices-ii.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
// Time: O((m + nlogn) * logm)
// Space: O(n)
// binary search, greedy, heap
class Solution {
public:
int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& changeIndices) {
vector<int> lookup(size(nums), -1);
for (int i = size(changeIndices) - 1; i >= 0; --i) {
if (nums[changeIndices[i] - 1]) {
lookup[changeIndices[i] - 1] = i;
}
}
const int64_t total = accumulate(cbegin(nums), cend(nums), 0ll) + size(nums);
const auto& check = [&](int t) {
priority_queue<int, vector<int>, greater<int>> min_heap;
int64_t total2 = 0, cnt = 0;
for (int i = t - 1; i >= 0; --i) {
if (i != lookup[changeIndices[i] - 1]) {
++cnt;
continue;
}
min_heap.emplace(nums[changeIndices[i] - 1]);
total2 += nums[changeIndices[i] - 1];
if (cnt) {
--cnt;
} else {
++cnt;
total2 -= min_heap.top(); min_heap.pop();
}
}
return total - (total2 + (size(min_heap))) <= cnt;
};
int64_t total2 = 0;
for (int i = 0; i < size(nums); ++i) {
total2 += lookup[i] != -1 ? 1 : nums[i];
}
int64_t left = total2 + size(nums), right = size(changeIndices);
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left <= size(changeIndices) ? left : -1;
}
};