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