-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-x-sum-of-all-k-long-subarrays-ii.cpp
53 lines (50 loc) · 1.69 KB
/
find-x-sum-of-all-k-long-subarrays-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
51
52
53
// Time: O(nlogn)
// Space: O(n)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
// freq table, ordered set, two pointers, sliding window
class Solution {
public:
vector<long long> findXSum(vector<int>& nums, int k, int x) {
using ordered_set = tree<pair<int, int64_t>, null_type, greater<pair<int, int64_t>>, rb_tree_tag, tree_order_statistics_node_update>;
ordered_set os;
unordered_map<int, int64_t> cnt;
const auto& update = [&](int v, int64_t d, int64_t curr) {
if (d == 1) {
os.insert({cnt[v], v});
}
if (os.order_of_key(pair(cnt[v], v)) < x) {
curr += d * cnt[v] * v;
if (x < size(os)) {
const auto [nc, nv] = *(os.find_by_order(x));
curr -= d * nc * nv;
}
}
if (d != 1) {
os.erase(pair(cnt[v], v));
}
return curr;
};
vector<long long> result;
for (int64_t i = 0, curr = 0; i < size(nums); ++i) {
if (cnt.count(nums[i])) {
curr = update(nums[i], -1, curr);
}
++cnt[nums[i]];
curr = update(nums[i], +1, curr);
if (i < k - 1) {
continue;
}
result.emplace_back(curr);
curr = update(nums[i - (k - 1)], -1, curr);
--cnt[nums[i - (k - 1)]];
if (cnt[nums[i - (k - 1)]]) {
curr = update(nums[i - (k - 1)], +1, curr);
} else {
cnt.erase(nums[i - (k - 1)]);
}
}
return result;
}
};