일정한 범위를 가지고 있는 것을 유지하면서 이동하는 것.
/*
문제
Write a function called maxSubarraySum which accepts
an array of integers and a number called n. The function
should calculate the maximum sum of n consecutive
elements in the array.
*/
function maxSubarraySum_(arr, num) {
let maxSum = 0;
let tempSum = 0;
if (arr.length < num) return null;
for (let i = 0; i < num; i++) {
maxSum += arr[i];
}
tempSum = maxSum;
for (let i = num; i < arr.length; i++) {
tempSum = tempSum - arr[i - num] + arr[i];
maxSum = Math.max(maxSum, tempSum);
}
return maxSum;
}
console.log(maxSubarraySum_([1, 2, 5, 2, 8, 1, 5], 2)); // 10
console.log(maxSubarraySum_([1, 2, 5, 2, 8, 1, 5], 4)); // 17
console.log(maxSubarraySum_([4, 2, 1, 6], 1)); // 6
console.log(maxSubarraySum_([4, 2, 1, 6, 2], 4)); // 13
console.log(maxSubarraySum_([], 4)); // null
console.log(maxSubarraySum_([2, 3, 1, 7, 2, 2, 9, 1, 3, 5, 2, 3, 4, 5, 6], 4)); // 20