fork download
  1. //
  2. // main.cpp
  3. // Number of subarray with given sum
  4. //
  5. // Created by Himanshu on 18/09/21.
  6. //
  7.  
  8.  
  9. #include <iostream>
  10. #include <climits>
  11. using namespace std;
  12. const int N = 7;
  13.  
  14. int solve (int A[], int k) {
  15.  
  16. int num = 0, currSum = A[0], start = 0, j;
  17.  
  18. for (int i=1; i<=N; i++) {
  19. for (j = start; currSum > k && j < (i-1); j++) {
  20. currSum = currSum - A[j];
  21. }
  22. start = j;
  23.  
  24. if (currSum == k) {
  25. num++;
  26. }
  27.  
  28. if (i<N) {
  29. currSum += A[i];
  30. }
  31. }
  32.  
  33. return num;
  34. }
  35.  
  36. int main() {
  37. int A[N] = {5, 3, 4, 6, 8, 11, 20};
  38. int k = 7;
  39.  
  40. cout<<"Number of subarray with sum "<<k<<": "<<solve(A, k)<<endl;
  41.  
  42. k = 4;
  43. cout<<"Number of subarray with sum "<<k<<": "<<solve(A, k)<<endl;
  44.  
  45. }
  46.  
  47.  
Success #stdin #stdout 0s 5468KB
stdin
Standard input is empty
stdout
Number of subarray with sum 7: 1
Number of subarray with sum 4: 1