东方博宜OJ 1683:递归法求最大值 ← 递归

【题目来源】
https://oj.czos.cn/p/1683

【题目描述】
请使用递归求 N 个数中的最大数及其位置。

【输入格式】
第一行一个整数 N,N≤1000。
第二行,N 个不重复的整数。

【输出格式】
最大值和其位置。

【输入样例】
10
2 4 1 6 3 10 9 7 8 5

【输出样例】
10 6

【数据范围】
N≤1000

【算法分析】
● 要善于变通,要学会从不同角度进行思考,来构建递归函数。

【算法代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e3+5;
int a[maxn];

int f(int n) { //求前n个数的最大值的下标
    if(n==1) return 1;
    int x=f(n-1);
    if(a[x]>a[n]) return x;
    else return n;
}

int main() {
    int n;
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>a[i];
    }

    cout<<a[f(n)]<<" "<<f(n);

    return 0;
}

/*
in:
10
2 4 1 6 3 10 9 7 8 5

out:
10 6
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/156211550
https://blog.csdn.net/hnjzsyjyj/article/details/156206151
https://blog.csdn.net/hnjzsyjyj/article/details/156206554
https://blog.csdn.net/hnjzsyjyj/article/details/156201255
https://blog.csdn.net/hnjzsyjyj/article/details/156192874
https://blog.csdn.net/hnjzsyjyj/article/details/156204715
https://blog.csdn.net/hnjzsyjyj/article/details/156185382
https://blog.csdn.net/hnjzsyjyj/article/details/156182882
https://www.bilibili.com/video/BV1TW4y1K7YK/

posted @ 2025-12-25 06:48  Triwa  阅读(4)  评论(0)    收藏  举报