← All Exercises

Maximum Sum of a Fixed-Size Window

intermediatepython~20min

Background

Sliding windows avoid recomputing every subarray sum: add the entering value, remove the leaving value, and keep the best result seen so far.

Problem

Given a list of integers and a window size k, return the maximum sum of any contiguous subarray of exactly k elements. Return None when k is not positive or the list is shorter than k.

Input

nums, a list of integers, and k, a positive window length.

Output

The maximum window sum as an integer, or None when no window of length k exists.

Sample tests

Sample 1

Input: nums = [2, 1, 5, 1, 3, 2], k = 3
Expected: 9

Sample 2

Input: nums = [4, -2, 3], k = 2
Expected: 2

Sample 3

Input: nums = [1], k = 3
Expected: None

Your solution

Learning objective

Recognize fixed-size sliding window problems and replace repeated O(n*k) summation with an O(n) pass.