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