Forked from scaryguy/window_sliding_in_javascript.js
Created
January 28, 2023 12:14
-
-
Save georgebullock/2f5c922061ef81c3fef64fc4242f9852 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