-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-inversion-count-in-subarrays-of-fixed-length.cpp
More file actions
58 lines (52 loc) · 1.46 KB
/
minimum-inversion-count-in-subarrays-of-fixed-length.cpp
File metadata and controls
58 lines (52 loc) · 1.46 KB
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
// Time: O(nlogn)
// Space: O(n)
// sort, coordinate compression, fenwick tree, sliding window
class BIT {
public:
BIT(int n) : bit_(n + 1) { // 0-indexed
}
void add(int i, int val) {
++i;
for (; i < size(bit_); i += lower_bit(i)) {
bit_[i] += val;
}
}
int query(int i) const {
++i;
int total = 0;
for (; i > 0; i -= lower_bit(i)) {
total += bit_[i];
}
return total;
}
private:
inline int lower_bit(int i) const {
return i & -i;
}
vector<int> bit_;
};
class Solution {
public:
long long minInversionCount(vector<int>& nums, int k) {
vector<int> vals(nums);
ranges::sort(vals);
vals.erase(unique(begin(vals), end(vals)), end(vals));
unordered_map<int, int> val_to_idx;
for (int i = 0; i < size(vals); ++i) {
val_to_idx[vals[i]] = i;
}
int64_t result = numeric_limits<int64_t>::max(), cnt = 0;
BIT bit(size(val_to_idx));
for (int i = 0; i < size(nums); ++i) {
bit.add(val_to_idx[nums[i]], +1);
cnt += bit.query(size(val_to_idx) - 1) - bit.query(val_to_idx[nums[i]]);
if (i < k - 1) {
continue;
}
result = min(result, cnt);
cnt -= bit.query(val_to_idx[nums[i - (k - 1)]] - 1);
bit.add(val_to_idx[nums[i - (k - 1)]], -1);
}
return result;
}
};