Array Max Consecutive Sum
Given array of integers, find the maximal possible sum of its k
consecutive elements.
Example
For inputArray = [2, 3, 5, 1, 6]
and k = 2
, the output should be
array_max_consecutive_sum(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 is8
.
Input/Output
[input] array.integer inputArray
Array of positive integers.
Guaranteed constraints:
3 ≤ inputArray.length ≤ 105
,1 ≤ inputArray[i] ≤ 1000
.[input] integer k
An integer (not greater than the length of
inputArray
).
Solution
py
def array_max_consecutive_sum(input_list, k):
max_sum = current_sum = sum(input_list[:k])
for i in range(len(input_list) - k):
current_sum += input_list[i + k] - input_list[i]
max_sum = max(max_sum, current_sum)
return max_sum
print(array_max_consecutive_sum([2, 3, 5, 1, 6], 2))
js
function arrayMaxConsecutiveSum(inputArray, k) {
let max = 0;
for (let i = 0; i < inputArray.length - k + 1; i++) {
let sum = 0;
for (let j = i; j < i + k; j++) {
sum += inputArray[j];
}
if (sum > max) {
max = sum;
}
}
return max;
}
console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));