반응형

Given array of integers, find the maximal possible sum of some of its k consecutive elements.


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.


code>>


int arrayMaxConsecutiveSum(std::vector<int> inputArray, int k)

{

int max = 0;

for (int i = 0; i < k; i++)

max += inputArray[i];

int tmp = max;

for (int i = 1; i < inputArray.size() - k + 1; i++)

{

tmp -= inputArray[i - 1];

tmp += inputArray[i + k - 1];

max = std::max(tmp, max);

}

return max;

}

반응형

'알고리즘 > codefights' 카테고리의 다른 글

39>knapsackLight  (0) 2017.08.08
38>growingPlant  (0) 2017.08.07
36>differentSymbolsNaive  (0) 2017.07.31
35>firstDigit  (0) 2017.07.31
34>extractEachKth  (0) 2017.07.31

+ Recent posts