Skip to content
Katabench
Try free

Max Sum Subarray of Size K

Easy About 10 min Free, no account needed

The biggest sum any window of exactly k elements can reach.

The brief

Given an integer array nums and an integer k (1 <= k <= nums.Length), return the maximum sum of any contiguous subarray of exactly k elements.

The performance bar

The obvious approach recomputes each window sum from scratch, O(n * k). The hidden test uses 200,000 elements with k = 100,000: twenty billion additions, far too slow. You will need an approach that does not redo work for overlapping windows.

Starter code

C#
using System;

public class Solution
{
    // TODO: return the maximum sum over all contiguous windows of exactly k elements.
    public long MaxSumOfSizeK(int[] nums, int k)
    {
        throw new NotImplementedException();
    }
}

How it is graded

Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.

C# coding challenges →

Related guides

What it practices

Sliding window
Grow and shrink a contiguous range while maintaining its state incrementally.

Related katas