//
// main.cpp
// Number of subarray with given sum
//
// Created by Himanshu on 18/09/21.
//
#include <iostream>
#include <climits>
using namespace std;
const int N = 7;
int solve (int A[], int k) {
int num = 0, currSum = A[0], start = 0, j;
for (int i=1; i<=N; i++) {
for (j = start; currSum > k && j < (i-1); j++) {
currSum = currSum - A[j];
}
start = j;
if (currSum == k) {
num++;
}
if (i<N) {
currSum += A[i];
}
}
return num;
}
int main() {
int A[N] = {5, 3, 4, 6, 8, 11, 20};
int k = 7;
cout<<"Number of subarray with sum "<<k<<": "<<solve(A, k)<<endl;
k = 4;
cout<<"Number of subarray with sum "<<k<<": "<<solve(A, k)<<endl;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBOdW1iZXIgb2Ygc3ViYXJyYXkgd2l0aCBnaXZlbiBzdW0KLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMTgvMDkvMjEuCi8vCgoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y2xpbWl0cz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKY29uc3QgaW50IE4gPSA3OwoKaW50IHNvbHZlIChpbnQgQVtdLCBpbnQgaykgewoKICAgIGludCBudW0gPSAwLCBjdXJyU3VtID0gQVswXSwgc3RhcnQgPSAwLCBqOwogICAgCiAgICBmb3IgKGludCBpPTE7IGk8PU47IGkrKykgewogICAgICAgIGZvciAoaiA9IHN0YXJ0OyBjdXJyU3VtID4gayAmJiBqIDwgKGktMSk7IGorKykgewogICAgICAgICAgICBjdXJyU3VtID0gY3VyclN1bSAtIEFbal07CiAgICAgICAgfQogICAgICAgIHN0YXJ0ID0gajsKICAgICAgICAKICAgICAgICBpZiAoY3VyclN1bSA9PSBrKSB7CiAgICAgICAgICAgIG51bSsrOwogICAgICAgIH0KICAgICAgICAKICAgICAgICBpZiAoaTxOKSB7CiAgICAgICAgICAgIGN1cnJTdW0gKz0gQVtpXTsKICAgICAgICB9CiAgICB9CgogICAgcmV0dXJuIG51bTsKfQogCmludCBtYWluKCkgewogICAgaW50IEFbTl0gPSB7NSwgMywgNCwgNiwgOCwgMTEsIDIwfTsKICAgIGludCBrID0gNzsKICAgIAogICAgY291dDw8Ik51bWJlciBvZiBzdWJhcnJheSB3aXRoIHN1bSAiPDxrPDwiOiAiPDxzb2x2ZShBLCBrKTw8ZW5kbDsKICAgIAogICAgayA9IDQ7CiAgICBjb3V0PDwiTnVtYmVyIG9mIHN1YmFycmF5IHdpdGggc3VtICI8PGs8PCI6ICI8PHNvbHZlKEEsIGspPDxlbmRsOwogICAgCn0KCg==