fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. int n;
  7. cin>>n;
  8. vector<int>arr(n,0);
  9. for(int i=0;i<n;i++){
  10. cin>>arr[i];
  11. }
  12. int k;
  13. cin>>k;
  14. int count=0;
  15. sort(arr.begin(),arr.end()); //need to sort for j>i
  16. for(int i=0;i<n;i++){
  17. for(int j=i+1;j<n;j++){
  18. int diff=arr[j]-arr[i];
  19. if(diff<=k){
  20. count++;
  21. }
  22. }
  23. }
  24. cout<<"Count of pairs with difference<=k:"<<count;
  25. return 0;
  26. }
Success #stdin #stdout 0s 5300KB
stdin
4
1 2 3 4
3
stdout
Count of pairs with difference<=k:6