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