Skip to content

Instantly share code, notes, and snippets.

@scaryguy
Created November 29, 2018 16:20
Show Gist options
  • Save scaryguy/289f69c1eceb70f66995cf64836f24de to your computer and use it in GitHub Desktop.
Save scaryguy/289f69c1eceb70f66995cf64836f24de to your computer and use it in GitHub Desktop.
Window Sliding Technique in JavaScript
// This gist is for my YouTube video which I tried to explain Window Sliding Technique.
// You can watch it from here: https://youtu.be/ZlnZkfEcbxs
//
// Given an array of integers of size ‘n’. Calculate the maximum sum possible
// for ‘k’ consecutive elements in the array.
//
// Input : [10, 20, 30, 40, 50, 60, 70]
//
// k = 3
// Output : 180
const arr = [10, 20, 30, 40, 50, 60, 70];
const k = 3;
function maxSum(arr, k) {
if (k > arr.length) {
return "invalid";
}
let windowTotal = 0;
for (let i = 0; i < k; i++) {
windowTotal += arr[i];
}
// const arr = [10, 20, 30, 40, 50, 60, 70];
// const k = 3;
let maxSumResult = windowTotal;
for (let i = k; i < arr.length; i++) {
windowTotal += arr[i] - arr[i - k];
maxSumResult = Math.max(windowTotal, maxSumResult);
}
return maxSumResult;
}
console.log(maxSum(arr, k));
@amarjeetdeveloper
Copy link

please write comment for better understanding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment