Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 5minslearn/f5fb22bec4cba7e39403bc59b55c8d44 to your computer and use it in GitHub Desktop.
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
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