fork download
  1. // TC : O(N^2)
  2. // SC : O(N)
  3.  
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int main() {
  8. int n;
  9. cin >> n;
  10.  
  11. int arr[n];
  12. for(int i=0; i<n; i++) {
  13. cin >> arr[i];
  14. }
  15.  
  16. int count = 0;
  17. int k;
  18. cin >> k;
  19.  
  20. int sum = 0;
  21.  
  22. // Subarray Template
  23. for(int i=0, j=0; j<n; j++) {
  24. sum += arr[j]; // [i .................... j]
  25. while(sum > k) {
  26. sum -= arr[j];
  27. i++;
  28. }
  29.  
  30. count += (j - i + 1);
  31. }
  32. cout << "Count : " << count;
  33. return 0;
  34. }
Success #stdin #stdout 0s 5308KB
stdin
5
1
2
2
5
8
4
stdout
Count : 9