Consecutive Sub Sequence

Problem

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}.

input

  • In the first line, N(1≤N≤100,000) and M(1≤M≤100,000,000) are given
  • The element value of a sequence is a natural number that does not exceed 1,000
86

1 2 1 3 1 1 1 2

output

Print the number of cases on the first line.

3

Solution

Only use while once

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;
}

Two Pointers Algorithm

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;
}