fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. vector<int> arr = {1, 2, 3, 4, 5};
  6. int k = 5;
  7. int n = arr.size();
  8.  
  9. unordered_map<int,int> freq;
  10. int prefix = 0, cnt = 0;
  11.  
  12. for (int x : arr) {
  13. prefix += x;
  14.  
  15.  
  16. if (prefix == k)
  17. cnt++;
  18.  
  19.  
  20. if (freq.find(prefix - k) != freq.end())
  21. cnt += freq[prefix - k];
  22.  
  23.  
  24. freq[prefix]++;
  25. }
  26.  
  27. cout << "no. of subarrays with sum " << k << " is " << cnt;
  28.  
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
no. of subarrays with sum 5 is 2