至少有两种方法可以解决您的问题。
第一个示例使用循环来计算峰值总和:
int peak_sum(int arr[], int size)
{
int sum = 0;
// check first element
if (arr[0] > arr[1]) {
std::cout << arr[0] << std::endl;
sum += arr[0];
}
// for each middle value in array
for (int i = 1; i < size - 2; i++) {
// if current value is peak
if(arr[i] > arr[i + 1] && arr[i] > arr[i - 1]) {
std::cout << arr[i] << std::endl;
// then we add it to total sum of peaks
sum += arr[i];
}
}
// check last element
if (arr[size - 1] > arr[size - 2]) {
std::cout << arr[size - 1] << std::endl;
sum += arr[size - 1];
}
// after all we return this sum of peaks
return sum;
}
但如果你想以递归方式解决它,那么它可能看起来像这样:
int
peak_sum(int arr[], int size, int index, int sum)
{
// if index in bounds
if (index < size) {
// if we on the first element
if (index == 0) {
// if first element more then next: it is peak
if (arr[index] > arr[index + 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}
// if we on the last element
} else if (index == size - 1) {
// if first element more then previous: it is peak
if (arr[index] > arr[index - 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}
// else we in the middle
} else {
// if current element more then previous and next: it is peak
if (arr[index] > arr[index - 1] && arr[index] > arr[index + 1]) {
std::cout << arr[index] << std::endl;
sum += arr[index];
}
}
// anyway we check next value of array
// by incrimeting current index
return peak_sum(arr, size, index + 1, sum);
} else {
// otherwise we end iterating array
return sum;
}
}
然后调用它:
// array, size of it, initial index, initial sum
peak_sum(arr, array_size, 0, 0);
如果您对代码流感兴趣:
//example for array_size == 3
if (index in bounds) {
index++;
if (index in bounds) {
index++;
if (index in bounds) {
index++;
if (index in bounds) {}
else return sum;
}
}
}