AlgoPrecision

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
5
Index 1
5
Index 2
5
Index 3
6
Index 4
8
Index 5R
11

Time

O(n)

Space

O(1)

Step Note

Use a fixed window size of 6.

Details
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
}