Consecutive Sub Sequence 2

Problem

You are given a sequence of N numbers.
Write a program to find how many times in this sequence the sum of consecutive subsequences is less than or equal to a specific number M.

If N=5, M=5 and the sequence is

1 3 1 2 3

A continuous subsequence whose sum is 5 or less is {1}, {3}, {1}, {2}, {3}, {1, 3}, {3, 1}, {1, 2}, {2 , 3}, {1, 3, 1}, for a total of 10.

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
55

1 3 1 2 3

output

Print the number of cases on the first line.

10

Solution

Only use while once

function solution(m, arr) {
	let answer = 0,
		start = 0,
		index = 0,
		sum = 0;

	while (index < arr.length) {
		sum += arr[index++];

		if (sum <= m) {
			answer++;
		} else {
			start++;
			index = start;
			sum = 0;
		}
	}
	if (arr[arr.length - 1] <= m) answer++;

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

		while (sum > m) {
			sum -= arr[lt++];
		}

		answer += rt - lt + 1;
	}

	return answer;
}