## 递归返回和基本流程应该怎么理解？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (221)

``````int  peak(int arr[],int i,int size)
{
while(i<size)
{
if(arr[i]>arr[i+1]&&arr[i]>arr[i-1])
cout<<arr[i];
i++;
return peak(arr,i,size);
}
}
``````

### 1 个回答

``````int peak_sum(int arr[], int size)
{
int sum = 0;

// for each value in array
for (int i = 1; i < size - 1; i++) {
// if current value is peak
if(arr[i] > arr[i+1] && arr[i] > arr[i-1]) {
cout << arr[i];
// then we add it to total sum of peaks
sum += arr[i];
}
}

// after all we return this sum of peaks
return sum;
}
``````

``````int peak_sum(int arr[], int size, int current_index, int sum)
{
// if index in bounds
if ((current_index > 0) && (current_index < size - 1)) {
// if current value is peak
if(arr[i] > arr[i+1] && arr[i] > arr[i-1]) {
cout << arr[i];
// then we add it to total sum of peaks
sum += arr[i];
}

// anyway we check next value of array
// by incrimeting `current_index`
return peak_sum(arr, size, current_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;
}
}
}
``````