import java.util.HashMap;
public class Main {
public static int countPairsWithDifferenceK(int[] b, int k) {
HashMap
<Integer, Integer
> freq
= new HashMap
<>(); int count = 0;
for (int j = 0; j < b.length; ++j) {
if (freq.containsKey(b[j] - k)) {
count += freq.get(b[j] - k);
}
if (k != 0 && freq.containsKey(b[j] + k)) { // to avoid double counting when k = 0
count += freq.get(b[j] + k);
}
freq.put(b[j], freq.getOrDefault(b[j], 0) + 1);
}
return count;
}
public static void main
(String[] args
) { int[] b = {1, 5, 3, 4, 2};
int k = 2;
System.
out.
println(countPairsWithDifferenceK
(b, k
)); // Output should be the number of pairs with difference k }
}
aW1wb3J0IGphdmEudXRpbC5IYXNoTWFwOwogCnB1YmxpYyBjbGFzcyBNYWluIHsKICAgIHB1YmxpYyBzdGF0aWMgaW50IGNvdW50UGFpcnNXaXRoRGlmZmVyZW5jZUsoaW50W10gYiwgaW50IGspIHsKICAgICAgICBIYXNoTWFwPEludGVnZXIsIEludGVnZXI+IGZyZXEgPSBuZXcgSGFzaE1hcDw+KCk7CiAgICAgICAgaW50IGNvdW50ID0gMDsKIAogICAgICAgIGZvciAoaW50IGogPSAwOyBqIDwgYi5sZW5ndGg7ICsraikgewogICAgICAgICAgICBpZiAoZnJlcS5jb250YWluc0tleShiW2pdIC0gaykpIHsKICAgICAgICAgICAgICAgIGNvdW50ICs9IGZyZXEuZ2V0KGJbal0gLSBrKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAoayAhPSAwICYmIGZyZXEuY29udGFpbnNLZXkoYltqXSArIGspKSB7IC8vIHRvIGF2b2lkIGRvdWJsZSBjb3VudGluZyB3aGVuIGsgPSAwCiAgICAgICAgICAgICAgICBjb3VudCArPSBmcmVxLmdldChiW2pdICsgayk7CiAgICAgICAgICAgIH0KIAogICAgICAgICAgICBmcmVxLnB1dChiW2pdLCBmcmVxLmdldE9yRGVmYXVsdChiW2pdLCAwKSArIDEpOwogICAgICAgIH0KIAogICAgICAgIHJldHVybiBjb3VudDsKICAgIH0KIAogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIGludFtdIGIgPSB7MSwgNSwgMywgNCwgMn07CiAgICAgICAgaW50IGsgPSAyOwogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbihjb3VudFBhaXJzV2l0aERpZmZlcmVuY2VLKGIsIGspKTsgLy8gT3V0cHV0IHNob3VsZCBiZSB0aGUgbnVtYmVyIG9mIHBhaXJzIHdpdGggZGlmZmVyZW5jZSBrCiAgICB9Cn0=