I need to calculate the sum of all k-sized sub-arrays in an array using sliding window algorithm. Is that a valid sliding window algorithm? If not, why?
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));
Should return 27
2
Answers
I analysed your code and it is actually window sliding algorithm, but done in a bit different way than I’m used to. I’d do it by moving the "window" a bit differently and not going from 0 index twice, but from the last visited index.
Difference is on how we move "the tail" – I move it by subtracting "k" and you by adding it.
My way of doing it would be this:
Reduce the array, as long as the index is lesser than
k
just add the current number to thetotal
, andsubTotal
. Afterwards calculate thenewSubTotal
by adding the current number to the lastnewSubTotal
, and removing the 1st number used for creating the previoussubTotal
. Add thenewSubTotal
to thetotal
to get the newtotal
.