Created
November 29, 2018 16:20
-
-
Save scaryguy/289f69c1eceb70f66995cf64836f24de to your computer and use it in GitHub Desktop.
Window Sliding Technique in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please write comment for better understanding