taesik

Write a function called maxSubarraySum which accepts an array of integers and a number called n. 본문

functions and trick/typescript_javascript

Write a function called maxSubarraySum which accepts an array of integers and a number called n.

taesikk 2022. 4. 29. 11:39

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