I am working through a coding challenge. The challenge basically wants me to find the max sum of its k consecutive elements. Here is an example:
For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be
arrayMaxConsecutiveSum(inputArray, k) = 8.
All possible sums of 2 consecutive elements are:
2 + 3 = 5;
3 + 5 = 8;
5 + 1 = 6;
1 + 6 = 7.
Thus, the answer is 8.
This is my attempt. I looked at the consecutive sum as sub-lists. So if I have k=3, then I have to add the 2 elements following i. So if the beginning is index 0, then the end is beginning + k-1. Then I tried to use a for loop to append the sum of every k chunks to a new list. My end goal was to return the max() from this list:
def arrayMaxConsecutiveSum(inputArray, k):
begin = 0
end = begin + (k-1)
sum_list = []
for i in range(0, len(inputArray)):
begin = i
sum_list.append(sum(inputArray[begin:end+1]))
print(sum_list)
Now I just wanted to see what my sum_list looked like before I tried to return its max. However, this is what it returns for a test case:
Input: inputArray: [2, 3, 5, 1, 6]
k: 2
Output: null
Expected Output: 8
Console Output: [5, 3, 0, 0, 0]
I think my logic is correct. I would just like to know where it is that I am making a mistake.