Is it possible to calculate the sum of all k-sized sub-arrays in an array using a sliding window algorithm? Is this approach valid, and if not, what are the reasons behind it?
var sumOfSubArrays = function(arr, k) {
let currentSubArray = 0;
for(let i=0; i<k; i++) {
currentSubArray += arr[i];
}
let sum = currentSubArray;
for(let i=0; i<arr.length-k; i++) {
sum += currentSubArray - arr[i] + arr[i+k];
currentSubArray = currentSubArray - arr[i] + arr[i+k];
}
return sum;
};
let arr = [1,2,3,4,5]
let k = 3;
console.log(sumOfSubArrays(arr, k));
Expected output should be 27