Created
January 9, 2024 17:33
-
-
Save 5minslearn/c4867d2750d89f81c8d72cc8bbacf700 to your computer and use it in GitHub Desktop.
Find maximum sum of a sub-array of size k - Native method
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 maxSum = -Infinity; | |
for (let i = 0; i <= listOfItems.length - sequenceLength; i++) { | |
let sum = 0; | |
for (let j = i; j < i + sequenceLength; j++) { | |
sum += listOfItems[j]; | |
} | |
maxSum = Math.max(maxSum, sum); | |
} | |
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