Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-016

Maximum Sum Subarray of Size K

Problem

Given a list of integers arr and an integer k, return the largest sum among all contiguous subarrays of length exactly k.

Use a fixed-size sliding window: add the entering element and remove the leaving one to update the sum in O(1). Return None if k <= 0 or the list is shorter than k; values may be negative.

Hint

Slide the window one step at a time and compare each new window sum with the best so far.

Test cases

case 1
in: [[2,1,5,1,3,2],3]
expected: 9
case 2
in: [[1],1]
expected: 1
case 3
in: [[1,2],3]
expected: null
case 4
in: [[-3,-1,-2],2]
expected: -3
case 5
in: [[-5,4,-1,2],2]
expected: 3
Starter codePython
def max_sum_subarray_k(arr, k):
    # Your code here
    pass

5 test cases · run your code against them in the editor