Arrays And Strings
Sliding Window
Slide a fixed-size window across the array while updating the running sum in constant time.
O(n) time / O(1) space
window size: 6sum: 0
Index 0L
5Index 1
5Index 2
5Index 3
6Index 4
8Index 5R
11Time
O(n)
Space
O(1)
Step Note
Use a fixed window size of 6.
function maxWindowSum(values: number[], size: number) {
let sum = 0
let best = -Infinity
for (let index = 0; index < values.length; index++) {
sum += values[index]
if (index >= size - 1) {
best = Math.max(best, sum)
sum -= values[index - size + 1]
}
}
return best
}