Sliding Window
Sliding Window is a technique for working with arrays or strings. Instead of using nested loops (slow), you maintain a window that slides through the data (fast). Use it when you need to find a subarray or substring that meets some condition.
// Find max sum of k consecutive numbers
function maxWindowSum(nums: number[], k: number): number {
// Calculate first window
let windowSum = nums.slice(0, k).reduce((total, val) => total + val, 0)
let maxSum = windowSum
// Slide the window
for (let i = k; i < nums.length; i++) {
windowSum += nums[i] - nums[i - k] // add new, remove old
maxSum = Math.max(maxSum, windowSum)
}
return maxSum
}
maxWindowSum([2, 1, 5, 1, 3, 2], 3) // 9 (5+1+3)