Skip to content

Commit d7e5de1

Browse files
authored
Create mark-elements-on-array-by-performing-queries.cpp
1 parent ddee558 commit d7e5de1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Time: O(q + nlogn)
2+
// Space: O(n)
3+
4+
// hash table, heap
5+
class Solution {
6+
public:
7+
vector<long long> unmarkedSumArray(vector<int>& nums, vector<vector<int>>& queries) {
8+
long long total = accumulate(cbegin(nums), cend(nums), 0ll);
9+
vector<bool> lookup(size(nums));
10+
vector<pair<int, int>> arr(size(nums));
11+
for (int i = 0; i < size(nums); ++i) {
12+
arr[i] = {nums[i], i};
13+
}
14+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap(cbegin(arr), cend(arr));
15+
vector<long long> result(size(queries));
16+
for (int i = 0; i < size(queries); ++i) {
17+
const int idx = queries[i][0];
18+
const int k = queries[i][1];
19+
if (!lookup[idx]) {
20+
lookup[idx] = true;
21+
total -= nums[idx];
22+
}
23+
for (int _ = 0; _ < k; ++_) {
24+
while (!empty(min_heap)) {
25+
const auto [x, i] = min_heap.top(); min_heap.pop();
26+
if (lookup[i]) {
27+
continue;
28+
}
29+
lookup[i] = true;
30+
total -= x;
31+
break;
32+
}
33+
if (empty(min_heap)) {
34+
break;
35+
}
36+
}
37+
result[i] = total;
38+
}
39+
return result;
40+
}
41+
};

0 commit comments

Comments
 (0)