Workspace

Problem workspace

3 day streakD

Maximum Sum of a Size-K Subarray

EasySliding WindowFixed windows

The challenge

Return the largest sum among all contiguous subarrays of exactly k elements.

Use 1 ≤ k ≤ n. Values may be negative. Indices are zero-based.

Example

[2, 1, 5, 1, 3, 2], k = 3 → 9, from [5, 1, 3].

Use the walkthrough below to inspect the input and each state change.

See Fixed-size sum, step by step

Expand, shrink, and inspect the window state.

6 elements · zero-based indicesk = 3
Sliding window over 6 elementsThe current window is empty. Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.Empty window · L = 0, R = -1201152133425
Current windowRecorded answerOutside window
Left
0
Right
-1
Length
0
Step 01 / 12

Start with an empty window

Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.

left = 0; right = −1

Answer so far

0
View exact input

Input: [2,1,5,1,3,2] · k = 3

Current window is empty.

Put it into code

Build the first sum once. Each slide adds one value and removes one value. Divide the best sum by k to get the maximum fixed-window average.

Indices are zero-based. C++ uses C++17 or later.

def max_window_sum(nums, k):
    # Contract: 1 <= k <= len(nums).
    total = sum(nums[:k])
    best = total  # Correct even when every value is negative.
    for right in range(k, len(nums)):
        total += nums[right] - nums[right - k]
        best = max(best, total)
    return best

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap