fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Method 1 while loop -->
  5. int subArrayCount(vector<int> &arr, int k){
  6.  
  7. int count = 0, i = 0, j = 0, sum = 0;
  8. while (j < arr.size()){
  9.  
  10. sum += arr[j];
  11.  
  12. while (sum > k){
  13. sum -= arr[i];
  14. i++;
  15. }
  16.  
  17. count += j-i+1;
  18. j++;
  19.  
  20. }
  21.  
  22. return count;
  23. }
  24.  
  25. // method - 2 for loop
  26. // int subArrayCount(vector<int> &arr, int k){
  27.  
  28. // int n = arr.size();
  29.  
  30. // int count = 0,sum = 0;
  31. // for (int i = 0, j = 0; j < n; j++){
  32.  
  33. // sum += arr[j];
  34.  
  35. // while (sum > k){
  36. // sum -= arr[i];
  37. // i++;
  38. // }
  39.  
  40. // count += j-i+1;
  41.  
  42. // }
  43.  
  44. // return count;
  45. // }
  46.  
  47. int main() {
  48. vector<int> arr = {1, 1, 2, 8, 1, 1};
  49. cout << subArrayCount(arr, 4);
  50. return 0;
  51. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
9