/*
문제
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, n) {
if (arr.length < n) {
return null;
}
let sum = 0;
for (let i = 0; i < n; i++) {
sum += arr[i];
}
for (let i = 1; i <= arr.length - n; i++) {
let tmp = 0;
for (let j = i; j < i + n; j++) {
tmp += arr[j];
}
if (sum < tmp){
sum = tmp;
}
}
return sum;
}
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
설명
let idx = 0;
for (let i = n; i <= arr.length; i++) {
if (arr[idx] < arr[i]){
sum = sum + arr[idx++] - arr[i]
}
}
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