Create a function that finds the maximum sum of any subarray of fixed size k in a given array of integers. Return -1 if k is invalid (k <= 0 or k > length of the array).
Examples:
max_subarray_sum_of_size_k([1,4,2,10,23,3,1,0,20], 4) returns 29 (subarray [4,2,10,23)
max_subarray_sum_of_size_k([-2, -3, -1, -4], 2) returns -3
def max_subarray_sum_of_size_k(arr, k):
"""One-line docstring placeholder"""
pass
Rules:
- Any language or pseudocode is fine. The stub just shows the shape.
- Say the time complexity of your approach.
- short rule
- O(n) time, O(1) extra space
- works for negative numbers
- edge case handling for invalid k
Post your solution as a reply. Answer goes up in about a day.
Challenge solution: Edge cases: ensure k is validated and handle all-negative arrays with correct sliding window
One way to do it:
def max_subarray_sum_of_size_k(arr, k):
"""Return the maximum sum of any subarray of length k.
If k is invalid (k <= 0 or k > len(arr)), return -1.
Uses a sliding window to achieve O(n) time and O(1) extra space.
"""
n = len(arr)
if k <= 0 or k > n:
return -1
# compute sum of first window
window_sum = sum(arr[:k])
max_sum = window_sum
# slide the window across the array
for i in range(k, n):
window_sum += arr[i] - arr[i - k]
if window_sum > max_sum:
max_sum = window_sum
return max_sum
Why:
This algorithm maintains a running sum of a fixed-size window and updates the maximum sum as it slides. It handles negative numbers correctly because it compares sums after each slide. The most important edge case is when k is invalid or equals the array length; in those cases, it returns -1 as specified.
First-answer leaderboard
- @emmawalter5 - 15 (firsts)

- @Apexcodes - 9 (firsts)
- @kirupa - 8 (firsts)
- @PipMuse - 5 (firsts)
- @adnanahmed - 2 (firsts)
Nice, this is clean. My favorite part is initializing max_sum to the first window instead of 0 — that’s the bit most people get wrong on this one, and it’s exactly what makes the all-negative case work instead of cheerfully returning 0 for an array that doesn’t contain a 0.
One small thing I’d flag: returning -1 for an invalid k can bite you, since -1 is also a perfectly valid answer (e.g. [-1, -2] with k=1). A caller can’t tell “bad input” apart from “the max sum really is -1.” Raising a ValueError, or returning None, would make that unambiguous.
Solid solution though — the slide itself is about as tight as it gets.