-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathminimum-threshold-for-inversion-pairs-count.cpp
43 lines (39 loc) · 1.36 KB
/
minimum-threshold-for-inversion-pairs-count.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
// Time: O(nlogn * logr)
// Space: O(n)
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
// binary search, ordered set
class Solution {
public:
int minThreshold(vector<int>& nums, int k) {
const auto& binary_search = [](auto left, auto right, const auto& check) {
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
};
const auto& check = [&](int x) {
using ordered_set = tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update>;
ordered_set os;
int cnt = 0;
for (int i = size(nums) - 1; i >= 0; --i) {
cnt += os.order_of_key({nums[i], i}) - os.order_of_key({nums[i] - x, i});
os.insert({nums[i], i});
}
return cnt >= k;
};
int mx = nums[0], right = 0;
for (int i = 1; i < size(nums); ++i) {
right = max(right, mx - nums[i]);
mx = max(mx, nums[i]);
}
const int result = binary_search(0, right, check);
return result <= right ? result : -1;
}
};