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 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
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.
Related guides
What it practices
- Sliding window
- Grow and shrink a contiguous range while maintaining its state incrementally.
Related katas
- Longest Rising Streak Easy Free Measure a consecutive telemetry climb without rescanning every possible starting point.
- Find All Anagram Start Indices Medium Free Every position where an anagram of the pattern begins.
- Fruit Into Baskets Medium Free Longest stretch of trees using at most two fruit types.
- Longest Repeating Character Replacement Medium Free Longest uniform run you can create with k character replacements.