给定一系列自然数,找到给定大小为k的最大连续子阵列的总和。 示例:
int array = {3, 6, 90, 23, 7, 1, 8, 3};
int k = 3;
总和应为120(90 + 23 + 7)。
示例代码:
#include <stdio.h>
int main(void) {
int arraysize = 9;
int array[9] = {3, 6, 9, 20, 40, 60, 1, 2, 3};
int k = 3;
int max = 0;
int maxcurrent = 0;
for (int i = 0; i < (arraysize - k); i++) {
for (int j = 0; j < k; j++) {
maxcurrent += array[i + j];
}
if (maxcurrent > max) { max = maxcurrent; }
maxcurrent = 0;
}
printf("%d\n", max);
}