You are given a sequence of N numbers.
Write a program to count how many times in this sequence the sum of consecutive subsequences is a specific number M.
If N=8, M=6 and the sequence is
1 2 1 3 1 1 1 2
There are three consecutive subsequences whose sum is 6: {2, 1, 3}, {1, 3, 1, 1}, and {3, 1, 1, 1}.
86
1 2 1 3 1 1 1 2
Print the number of cases on the first line.
3
function solution(m, arr) {
let answer = 0,
sum = 0,
start = 0,
index = 0;
while (index < arr.length) {
sum += arr[index++];
if (sum === m) {
answer++;
} else if (sum > m) {
start++;
sum = 0;
index = start;
}
}
return answer;
}
function solution(m, arr) {
let answer = 0,
sum = 0,
lt = 0;
for (let rt = 0; rt < arr.length; rt++) {
sum += arr[rt];
if (sum === m) answer++;
while (sum >= m) {
sum -= arr[lt++];
if (sum === m) answer++;
}
}
return answer;
}