Maintained by Vikas Dulgunde, software engineer
You are handed an array of integers and a number k. Your job is to look at every contiguous run of exactly k consecutive elements and report the highest total any of those runs can produce.
A run here means a slice of the array with no gaps. The first valid run covers indices 0 through k-1, the next covers 1 through k, and so on until the window reaches the end of the array. Each of those runs has its own sum.
The array can hold negative numbers, so the answer is not always positive. When every element is negative, the best you can do is the run whose negative total is closest to zero.
Because k is at least 1 and never larger than the array length, at least one valid run always exists, so there is always an answer to return.
The length-3 runs sum to 8, 7, 9, and 6. The run [5, 1, 3] gives 9, the largest.
Adjacent pairs sum to 5, 7, 5, and 6. The pair [3, 4] reaches 7.
Every pair is negative, summing to -3, -5, and -7. The pair [-1, -2] is the least negative at -3.
Visible test cases
There are exactly nums.length - k + 1 runs to consider. Try writing the most direct loop that scores each one before optimizing.
Two neighboring runs overlap in all but two elements. When the window shifts right by one, only the element that leaves and the element that enters actually change.
Keep a running total. Add the incoming element and subtract the outgoing one each step instead of re-adding the whole window.
Compute the sum of each length-k run independently and track the maximum.
Build the sum of the first window once, then slide it across the array, adjusting by only the two elements that change at each step.