Easy
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.
Input/Output
-
[execution time limit] 0.5 seconds (c)
-
[input] array.integer inputArray
Array of positive integers.
Guaranteed constraints:
3 ≤ inputArray.length ≤ 10^5,
1 ≤ inputArray[i] ≤ 1000. -
[input] integer k
An integer (not greater than the length of inputArray).
Guaranteed constraints:
1 ≤ k ≤ inputArray.length. -
[output] integer
- The maximal possible sum.
[C] Syntax Tips
// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
char * answer = malloc(strlen(name) + 8);
printf("This prints to the console when you Run Tests");
strcpy(answer, "Hello, ");
strcat(answer, name);
return answer;
}
더보기
Solution
// Arrays are already defined with this interface:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
int arrayMaxConsecutiveSum(arr_integer inputArray,int k)
{
int max=0;
for(int i=0;i<inputArray.size-k+1;i++)
{
int sum=0;
for(int j=0;j<k;j++)
sum+=inputArray.arr[i+j];
max=sum>max?sum:max;
}
return max;
}
728x90
'Codesignal' 카테고리의 다른 글
<Codesignal> Knapsack Light (0) | 2020.04.05 |
---|---|
<Codesignal> growingPlant (0) | 2020.04.05 |
<Codesignal> differentSymbolsNaive (0) | 2020.04.05 |
<Codesignal> firstDigit (0) | 2020.04.05 |
<Codesignal> extractEachKth (0) | 2020.04.05 |