fork download
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <unordered_map>
  5. using namespace std;
  6. int countSubarrays(vector<int> &arr, int k) {
  7. unordered_map<int,int> mp;
  8. int c=0;int cur=0;
  9. for(int i:arr){
  10. cur+=i;
  11. if(cur==k) c+=1;
  12. if(mp.find(cur-k)!=mp.end()) c+=mp[cur-k];
  13. mp[cur]++;
  14. }
  15. return c;
  16.  
  17. }
  18.  
  19. int main() {
  20. vector<int> arr = {10, 2, -2, -20, 10};
  21. int k = -10;
  22. cout << countSubarrays(arr, k);
  23. return 0;
  24. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
3