fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int getCount(int n,vector<int>v,int k){
  4. int count=0;
  5. int sum=0;
  6. int i=0;
  7. for(int j=0;j<n;j++){
  8. sum+=v[j];
  9. while(sum>k){
  10. sum=sum-v[i];
  11. i++;
  12. }
  13. count=count+(j-i+1);
  14. }
  15. return count;
  16. }
  17.  
  18. int main() {
  19. // your code goes here
  20. int n;
  21. cin>>n;
  22. vector<int>v(n,0);
  23. for(int i=0;i<n;i++){
  24. cin>>v[i];
  25. }
  26. int k;
  27. cin>>k;
  28. cout<<"The number of subarray with sum less than k is:"<<getCount(n,v,k);
  29. return 0;
  30. }
Success #stdin #stdout 0.01s 5284KB
stdin
5
2 1 1 5 8
4
stdout
The number of subarray with sum less than k is:6