Maximum Sales

Problem

Hyun-soo’s father runs a bakery. Hyeon-soo’s father gave him the sales record for N days and told him to find the maximum sales for K consecutive days.

If N=10, the sales record for 10 days is as follows. In this case, if K = 3

12 15 11 20 25 10 20 19 13 15

The maximum sales for 3 consecutive days is 11+20+25=560,000 won.
Please help Hyun-soo.

input

  • The first line is given N(5<=N<=100,000) and M(2<=K<=N)
  • The second line gives N strings of numbers
  • Each number is a non-negative integer less than or equal to 500
10 3

12 15 11 20 25 10 20 19 13 15

output

Print the maximum sales on the first line.

56

Solution

Only use while once

function solution(k, arr) {
	let answer = 0,
		index = k - 1;

	while (index < arr.length) {
		if (arr[index - 2] + arr[index - 1] + arr[index] > answer) {
			answer = arr[index - 2] + arr[index - 1] + arr[index];
		}
		index++;
	}

	return answer;
}

Two Pointers Algorithm

function solution(k, arr) {
	let answer,
		sum = 0;

	for (let i = 0; i < k; i++) sum += arr[i];
	answer = sum;

	for (let i = k; i < arr.length; i++) {
		sum += arr[i] - arr[i - k];
		answer = Math.max(answer, sum);
	}

	return answer;
}