Last active
January 9, 2024 18:12
-
-
Save 5minslearn/f5fb22bec4cba7e39403bc59b55c8d44 to your computer and use it in GitHub Desktop.
Find maximum sum of sub-array of size k using sliding window technique
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
function findMaxSumOfSequence(listOfItems: number[], sequenceLength: number) { | |
if (listOfItems.length < sequenceLength) { | |
return null; | |
} | |
let start = 0, | |
end = 0, | |
maxSum = 0, | |
windowSum = 0; | |
while (end < sequenceLength) { | |
windowSum += listOfItems[end]; | |
end++; | |
maxSum = windowSum; | |
} | |
while (start + sequenceLength < listOfItems.length) { | |
windowSum = windowSum - listOfItems[start] + listOfItems[end]; | |
maxSum = Math.max(windowSum, maxSum); | |
start++; | |
end++; | |
} | |
return maxSum; | |
} | |
const input = [1, 2, 6, 2, 4, 1], | |
windowSize = 3; | |
console.log( | |
`Maximum sum of a sub-array of window size ${windowSize} is ${findMaxSumOfSequence( | |
input, | |
windowSize | |
)}` | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment