Skip to content

Commit ca8ae8d

Browse files
committed
Add C++ solution of problem #2364
1 parent 8c090e5 commit ca8ae8d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

2364/solution.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)