Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the maximum sum of a subarray of size K

Compute the maximum sum among all contiguous subarrays of fixed size K using a sliding window.

Python practice16 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given an array of integers arr and an integer K, return the maximum sum of any contiguous subarray of length K. If K is greater than the array length, return None.

Task

Use a variable update of the window sum to compute the maximum contiguous sum of size K in O(n) time.

Examples

Basic example

Input

arr = [2, 1, 5, 1, 3, 2], K = 3

Output

9

Subarray [5,1,3] has the maximum sum 9.

Input format

An array of integers arr and an integer K.

Output format

An integer equal to the maximum sum, or None if K > len(arr).

Constraints

1 <= K <= 10^5, len(arr) <= 10^5. Integers may be negative. Time O(n) and O(1) extra space.

Samples

Sample 1

Input

arr = [2, 3, 4, 1, 5], K = 2

Output

7

Subarray [3,4] has sum 7.