We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 8c090e5 commit ca8ae8dCopy full SHA for ca8ae8d
2364/solution.cpp
@@ -0,0 +1,24 @@
1
+class Solution {
2
+public:
3
+ long long countBadPairs(vector<int>& A) {
4
+ unordered_map<int, vector<int>> m; // {A[i] - i, {idxs}}
5
+ int n = A.size();
6
+
7
+ // preserve the monotonicaliation of index of pairs
8
+ for(int i = 0; i < n; i++)
9
+ m[A[i] - i].push_back(i);
10
11
+ long long ans = 0LL;
12
+ for(auto &[_, v] : m) {
13
+ int sz = v.size();
14
+ for(int i = 0; i < sz; i++) {
15
+ int idx = v[i];
16
+ int expected = (n - idx - 1); // expected pairs or current index
17
+ int good = (sz - i - 1); // the "good" pairs, i.e., i < j and j - i == A[j] - A[i]
18
19
+ ans += (expected - good); // get # the "bad" pairs
20
+ }
21
22
+ return ans;
23
24
+};
0 commit comments