-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorting15.cpp
More file actions
40 lines (36 loc) · 863 Bytes
/
Copy pathSorting15.cpp
File metadata and controls
40 lines (36 loc) · 863 Bytes
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
#include<bits/stdc++.h>
#define MAX 100000
int countPairsWithDiffK(int arr[], int n, int k)
{
int count = 0; // Initialize count
// Initialize empty hashmap.
bool hashmap[MAX] = {false};
// Insert array elements to hashmap
for (int i = 0; i < n; i++)
hashmap[arr[i]] = true;
for (int i = 0; i < n; i++)
{
int x = arr[i];
if (x - k >= 0 && hashmap[x - k])
count++;
if (x + k < MAX && hashmap[x + k])
count++;
hashmap[x] = false;
}
return count;
}
int main(){
int t;
std::cin>>t;
while (t--)
{
int n,k;
std::cin>>n>>k;
int arr[n];
for (int i = 0; i < n; i++)
{
std::cin>>arr[i];
}
std::cout <<countPairsWithDiffK(arr,n,k);
}
}