使用递归查找数组中的最大相对值

Finding the maxium relative in array by using recursion

本文关键字:相对 递归 查找 数组      更新时间:2023-10-16

找不到解决我的方法。

如果数组中的数字值大于其两个相邻值,则该数字是相对最大值。最大值是数字与其两个相邻数字之间的差值之和。编写一个程序,询问用户的数组大小(范围在 10 到 100 之间),用户应该插入数字(在 1 到 1000 之间),并调用递归函数来计算数组中出现的最大相对最大值,并打印它。示例(数组大小为 15)        24 28 22 4 6 7 8 6 5 11 10 21 9 4 13

应打印 23,因为 21(以

三个粗体显示)是 23 (21-10) + (21-9) = 23 的最大相对最大值

到目前为止,我所做的是创建进入函数的内容,但回避的想法让我很难。

#include <iostream>
using namespace std;
int rMax(int arr[],int arrSize)
{
}
int main()
{
    int arr[100], size;
    // input check
    do {
        cout << "Please enter size of array:" << endl;
        cin >> size;
    } while (size <= 0);
    cout << "Please enter " << size << " numbers:" << endl;
    //input loop
    for (int i = 0; i < size; i++)
    {
        cin >> arr[i];
    }

}

可以用类似的、较小的问题来描述你的问题时,递归是最好的。

让我们改写一下问题陈述

查找最能满足此数组中某些属性的元素

并将其分解为更小的子问题

在此数组的前半部分查找满足某些属性的元素

在此数组的后半部分查找满足某些属性的元素

然后,我们只需要考虑 2 个元素,然后选择更好的元素。通过再次调用函数来重复这种拆分,直到我们没有任何东西可以减半,我们在其中计算"一些属性"

草图

#include <vector>
#include <iostream>
int rMax(int * start, int * end)
{
    // Base case: we have only one element
    // We just calculate its "relative value"
    if (start == end)
        return (start[0] - start[-1]) + (start[0] - start[1]);
    // Recursive case: split into two halves and pick the best
    int * middle = start + ((end - start) / 2);
    int first = rMax(start, middle);
    int second = rMax(middle + 1, end);
    return std::max(first, second);        
}
int main()
{
    int size;
    // input check, need at least 3 elements to have any "relative maximum"
    do {
        std::cout << "Please enter size of array:" << std::endl;
        std::cin >> size;
    } while (size < 3);
    std::cout << "Please enter " << size << " numbers:" << std::endl;
    std::vector<int> arr(size);
    //input loop
    for (int i = 0; i < size; i++)
    {
        std::cin >> arr[i];
    }
    // don't consider the first or last element, as they have only one adjacent value
    std::cout << rMax(arr.data() + 1, arr.data() + size - 1);
}

递归在这里可以通过分而治之模式使用。关键是将数组分成 2 个部分,并在每个部分中找到相对最大值。当作品的大小为3时,答案显而易见。

关键是您必须在高部分之前保留一个元素,在低部分之后保留一个元素。顺便说一下,确保零件的最小尺寸为 3 就足够了。

但是您还必须将较高的相对最大值的(相对)索引及其值保留在一块中,以便能够比较两块的相对最大值,因此我建议您使用以下签名:

int rMax(int *arr, int size, int *index);   // returns the value of the relative max or 0

我让你写实际的实现(毕竟你必须练习)。如果您遇到写作困难,请随时提出一个新问题。