fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int countPairsWithDiffk(vector<int> &arr, int k){
  5. int n = arr.size();
  6. int count = 0;
  7.  
  8. for (int i = 0; i < n; i++){
  9.  
  10. for (int j = i+1; j < n; j++){
  11. int d = abs(arr[j] - arr[i]);
  12.  
  13. if (d <= k){
  14. count++;
  15. }
  16.  
  17. }
  18. }
  19.  
  20. return count;
  21. }
  22.  
  23. int main() {
  24. vector<int> arr = {1, 5, 3, 4, 2};
  25. cout << countPairsWithDiffk(arr, 2);
  26. return 0;
  27. }
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
7