teacher
Sign in

Sliding Window

Keep a moving range of the array and update its total as it grows and shrinks, instead of recomputing it each time.

35 minCF 1000–15005 interactive12 problems

The problem

Two questions that look alike:

  1. Given an array and a number k, find the largest sum of k consecutive elements.
  2. Given an array of positive numbers and a number s, find the shortest run of consecutive elements whose sum is at least s.

A run of consecutive elements is a window. Both questions ask about windows, so you inspect them one after another while sliding the window rightward.

1 of 10