#Given array of integers, find the sum of some of its k consecutive elements.
#Sample Input: #inputArray = [2, 3, 5, 1, 6] and k = 2
JavaScript
x
12
12
1
#Sample Output:
2
#arrayMaxConsecutiveSum(inputArray, k) = 8
3
4
#Explaination:
5
#All possible sums of 2 consecutive elements are:
6
7
#2 + 3 = 5;
8
#3 + 5 = 8;
9
#5 + 1 = 6;
10
#1 + 6 = 7.
11
#Thus, the answer is 8`
12
Advertisement
Answer
Your question is not clear but assuming you need a function to return the sum of the highest pair of numbers in your list:
JavaScript
1
13
13
1
def arrayMaxConsecutiveSum(inputArray, k):
2
groups = (inputArray[pos:pos + k] for pos in range(0, len(inputArray), 1)) # iterate through array creating groups of k length
3
highest_value = 0 # start highest value at 0
4
for group in groups: # iterate through groups
5
if len(group) == k and sum(group) > highest_value: # if group is 2 numbers and value is higher than previous value
6
highest_value = sum(group) # make new value highest
7
return highest_value
8
9
inputArray = [2, 3, 5, 1, 6]
10
11
print(arrayMaxConsecutiveSum(inputArray, 2))
12
#8
13