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