//
// main.cpp
// Subarray with sum
//
// Created by Himanshu on 18/09/21.
//
#include <iostream>
#include <climits>
#include <map>
using namespace std;
const int N = 7;
int subarraySum(int A[], int k) {
map<int, int > hmap;
int sum = 0, sol = 0;
hmap[0] = 1;
for (int i=0; i<N; i++) {
sum = sum + A[i];
if (hmap.find(sum-k) != hmap.end()) {
sol += hmap[sum-k];
}
hmap[sum] += 1;
}
return sol;
}
int main() {
int A[N] = {5, 2, 4, -6, -1, -1, 1};
int k = 6;
cout<<"Number of subarray with sum "<<k<<": "<<subarraySum(A, k)<<endl;
k = 0;
cout<<"Number of subarray with sum "<<k<<": "<<subarraySum(A, k)<<endl;
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTdWJhcnJheSB3aXRoIHN1bQovLwovLyAgQ3JlYXRlZCBieSBIaW1hbnNodSBvbiAxOC8wOS8yMS4KLy8KCiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPGNsaW1pdHM+CiNpbmNsdWRlIDxtYXA+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmNvbnN0IGludCBOID0gNzsKCmludCBzdWJhcnJheVN1bShpbnQgQVtdLCBpbnQgaykgewogICAgbWFwPGludCwgaW50ID4gaG1hcDsKICAgIGludCBzdW0gPSAwLCBzb2wgPSAwOwogICAgCiAgICBobWFwWzBdID0gMTsKICAgIAogICAgZm9yIChpbnQgaT0wOyBpPE47IGkrKykgewogICAgICAgIHN1bSA9IHN1bSArIEFbaV07CiAgICAgICAgaWYgKGhtYXAuZmluZChzdW0taykgIT0gaG1hcC5lbmQoKSkgewogICAgICAgICAgICBzb2wgKz0gaG1hcFtzdW0ta107CiAgICAgICAgfQogICAgICAgIGhtYXBbc3VtXSArPSAxOwogICAgfQoKICAgIHJldHVybiBzb2w7Cn0KCmludCBtYWluKCkgewogICAgaW50IEFbTl0gPSB7NSwgMiwgNCwgLTYsIC0xLCAtMSwgMX07CiAgICBpbnQgayA9IDY7CiAgICAKICAgIGNvdXQ8PCJOdW1iZXIgb2Ygc3ViYXJyYXkgd2l0aCBzdW0gIjw8azw8IjogIjw8c3ViYXJyYXlTdW0oQSwgayk8PGVuZGw7CiAgICAKICAgIGsgPSAwOwogICAgY291dDw8Ik51bWJlciBvZiBzdWJhcnJheSB3aXRoIHN1bSAiPDxrPDwiOiAiPDxzdWJhcnJheVN1bShBLCBrKTw8ZW5kbDsKICAgIAogICAgcmV0dXJuIDA7Cn0K