import java.util.HashMap;
import java.util.Map;
public class Main {
public static int countPairsOptimized(int[] b, int k) {
int count = 0;
Map
<Integer, Integer
> freqMap
= new HashMap
<>(); for (int j = 0; j < b.length; ++j) {
int target = b[j] + k;
if (freqMap.containsKey(target)) {
count += freqMap.get(target);
}
freqMap.put(b[j], freqMap.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("Count of pairs: " + countPairsOptimized
(b, k
)); }
}
aW1wb3J0IGphdmEudXRpbC5IYXNoTWFwOwppbXBvcnQgamF2YS51dGlsLk1hcDsKIApwdWJsaWMgY2xhc3MgTWFpbiB7CiAgICBwdWJsaWMgc3RhdGljIGludCBjb3VudFBhaXJzT3B0aW1pemVkKGludFtdIGIsIGludCBrKSB7CiAgICAgICAgaW50IGNvdW50ID0gMDsKICAgICAgICBNYXA8SW50ZWdlciwgSW50ZWdlcj4gZnJlcU1hcCA9IG5ldyBIYXNoTWFwPD4oKTsKICAgICAgICBmb3IgKGludCBqID0gMDsgaiA8IGIubGVuZ3RoOyArK2opIHsKICAgICAgICAgICAgaW50IHRhcmdldCA9IGJbal0gKyBrOwogICAgICAgICAgICBpZiAoZnJlcU1hcC5jb250YWluc0tleSh0YXJnZXQpKSB7CiAgICAgICAgICAgICAgICBjb3VudCArPSBmcmVxTWFwLmdldCh0YXJnZXQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZyZXFNYXAucHV0KGJbal0sIGZyZXFNYXAuZ2V0T3JEZWZhdWx0KGJbal0sIDApICsgMSk7CiAgICAgICAgfQogICAgICAgIHJldHVybiBjb3VudDsKICAgIH0KIAogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIGludFtdIGIgPSB7MSwgNSwgMywgNCwgMn07CiAgICAgICAgaW50IGsgPSAyOwogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiQ291bnQgb2YgcGFpcnM6ICIgKyBjb3VudFBhaXJzT3B0aW1pemVkKGIsIGspKTsKICAgIH0KfQ==