Skip to content

Instantly share code, notes, and snippets.

@5minslearn
Created January 9, 2024 17:33
Show Gist options
  • Save 5minslearn/c4867d2750d89f81c8d72cc8bbacf700 to your computer and use it in GitHub Desktop.
Save 5minslearn/c4867d2750d89f81c8d72cc8bbacf700 to your computer and use it in GitHub Desktop.
Find maximum sum of a sub-array of size k - Native method
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