注意边界情况
#include <iostream>
using namespace std;
/*
求树状中相邻n个数的最大值
*/
//辅助函数先计算数组前n项和
int getSumOfFrontNNUMS(int* arr, int len, int n) {
if (n == 0) {
return 0;
}
if (arr == NULL || len < 1 || n > len) {
throw new exception("out of range");
return -1;
}
else {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
}
int getMaxSumOfNearNNums(int* arr, int len, int n) {
if (n == 0) {
return 0;
}
if (arr == NULL || len < 1 || n > len ) {
throw new exception("out of range");
return 0;
}
else {
int i = n;
int maxSum = getSumOfFrontNNUMS(arr,len,n);
int curSum = maxSum;//记录当前n个数的和
int beginOfMaxSum = 0;//记录最大值开始的位置
int left = 0;//记录当前n个数字的最左端
while (i < len) {
curSum += arr[i] - arr[left];
if (curSum > maxSum) {
maxSum = curSum;
beginOfMaxSum = left;
}
i++;
left++;
}
return maxSum;
}
}