fork download
  1. import java.util.HashMap;
  2.  
  3. public class Main {
  4. public static int countPairsWithDifferenceK(int[] b, int k) {
  5. HashMap<Integer, Integer> freq = new HashMap<>();
  6. int count = 0;
  7.  
  8. for (int j = 0; j < b.length; ++j) {
  9. if (freq.containsKey(b[j] - k)) {
  10. count += freq.get(b[j] - k);
  11. }
  12. if (k != 0 && freq.containsKey(b[j] + k)) { // to avoid double counting when k = 0
  13. count += freq.get(b[j] + k);
  14. }
  15.  
  16. freq.put(b[j], freq.getOrDefault(b[j], 0) + 1);
  17. }
  18.  
  19. return count;
  20. }
  21.  
  22. public static void main(String[] args) {
  23. int[] b = {1, 5, 3, 4, 2};
  24. int k = 2;
  25. System.out.println(countPairsWithDifferenceK(b, k)); // Output should be the number of pairs with difference k
  26. }
  27. }
Success #stdin #stdout 0.08s 54676KB
stdin
Standard input is empty
stdout
3