educative.io

Error in logic for sliding window, edge case

The solution for sliding window fails when the size of subarray is given as 0.

This should be the right answer,

Input: [2, 1, 5, 1, 3, 2], k=0 Output: 0 Explanation: Subarray with maximum sum is [].

However, the solution gives 5 as the answer.

A subarray of size 0 has a sum of 0.

This code accommodates for the edge case:
def max_sub_array_of_size_k(k, arr):
_sum = 0
start_pointer=0;
end_pointer=0;
max_sum=0
_sum = 0
while(end_pointer<len(arr)):
if(end_pointer-start_pointer<k):
_sum += arr[end_pointer]
end_pointer += 1
else:
max_sum = max(_sum, max_sum)
_sum -= arr[start_pointer]
start_pointer += 1
return max_sum